如何从BroadCastReciever更改MainActivity元素

时间:2018-03-26 21:54:37

标签: android kotlin

我有一个BroadcastReceive,想根据广播中的逻辑更改/显示MainActivity中的视图文本

class Receiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
         // somthing like
        // MainActivity.layout.latitudeTxt = ....
   }
}

我的MainActivity如下:

private lateinit var layout: View
private lateinit var latitudeTxt: TextView
private lateinit var longitudeTxt: TextView

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        layout = main_layout
        latitudeTxt = latitudeText
        longitudeTxt = longitudeText
    }
}

1 个答案:

答案 0 :(得分:1)

您可以尝试以编程方式添加带有自定义侦听器的广播接收器,而不是在AndroidManifest中。你需要这些课程:

class Receiver(val receiverListener: ReceiverListener) : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
    // somthing like
    // MainActivity.layout.latitudeTxt = ....
    receiverListener.doSomething()
}

}

您可以更改此界面,使其适合您的要求(添加方法,更改签名等)。这是一种经典的回调技术。

interface ReceiverListener {
    fun doSomething()
}

然后在onCreate()注册接收者:

    receiver = Receiver(object : ReceiverListener {
        override fun doSomething() {
            //If you need to change smth related to UI
            runOnUiThread {

            }
        }
    })
    registerReceiver(receiver, IntentFilter("YOUR_ACTION"))

请勿忘记在onDestroy()

中取消注册