Android BroadcastReceiver onReceive Update TextView in MainActivity

后端 未结 5 1925
说谎
说谎 2020-12-01 04:04

In MainActivity I have a TextView: textV1. I also have a method in MainActivity that updates that textview:

public void updateTheTextView(final String t) {
         


        
5条回答
  •  鱼传尺愫
    2020-12-01 04:18

    If someone is searching this exact solution, but in Kotlin, do the following:

    class MainActivity : AppCompatActivity() {
    
        companion object {
            var ins: MainActivity? = null
            fun getInstance(): MainActivity? {
                return ins
            }
        }
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            ins = this
        }
    
        fun updateTheTextView(t: String) {
            this@MainActivity.runOnUiThread {
                val textV1 = findViewById(R.id.textV1)
                textV1.text = t
            }
        }
    }
    
    class NotifAlarm : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            try {
                MainActivity.getInstance()?.updateTheTextView("The String")
            } catch (e: Exception) {
    
            }
        }
    }
    

提交回复
热议问题