有人知道为什么我无法在ViewModel上下文中收听任何BroadcastReceiver吗?如果我在Activity,Fragment或Application本身内执行相同的代码,那么它将起作用。但是,从使用相同应用程序实例的ViewModel这样做,是行不通的。
这是基本代码:
class MyViewModel(application: Application) : AndroidViewModel(application) {
init {
registerBroadcastReceivers(application)
}
/**
* Register for required broadcast receivers.
*/
private fun registerBroadcastReceivers(application: Application) {
application
.registerReceiver(
mLocationProviderChangedReceiver,
IntentFilter(LocationManager.MODE_CHANGED_ACTION)
)
}
/**
* Broadcast receiver to monitor the changes in the location provider.
*/
private val mLocationProviderChangedReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Log.d("", "Received!") // <-- Never triggered when switching location
}
}
}
我发现an example可以完美地用Java编写,可以在AndroidViewmodel中使用相同的BroadcastReceiver,但是我仍然看不到虚拟项目中下面的代码有什么问题。