问题
This is my broadcast receiver class and the implementation of it in main.
Problem is that onReceive
method never gets called.
class MyBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(p0: Context?, p1: Intent?) {
Toast.makeText(p0, "It works", Toast.LENGTH_LONG).show()
}
}
class MainActivity : AppCompatActivity() {
......
private var broadcastReceiver: MyBroadcastReceiver = MyBroadcastReceiver()
override fun onCreate(savedInstanceState: Bundle?) {
......
registerReceiver(broadcastReceiver, IntentFilter().apply {
addAction(Intent.ACTION_PACKAGE_ADDED)
addAction(Intent.ACTION_PACKAGE_REMOVED)
})
}
override fun onDestroy() {
super.onDestroy()
unregisterReceiver(broadcastReceiver)
}
}
Please help. Thanks in advance.
回答1:
Usually the BroadcastReceiver
needs a number of steps to be set up.
First of all did yout pass to the manifest the receiver?
<receiver android:name=".MyBroadcastReceiver" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.INPUT_METHOD_CHANGED" />
</intent-filter>
</receiver>
Edit: Please see this post, where is suggested ACTION_PACKAGE_FULLY_REMOVED or JobScheduler
try also to reinstall the app on the emulator
回答2:
I could make it work with the following code
class KotlinBroadcastReceiver(action: (context: Context, intent: Intent) -> Unit) : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) = action(context, intent)
}
class MainActivity : AppCompatActivity() {
private val broadcastReceiver = KotlinBroadcastReceiver { context, _ ->
Toast.makeText(context, "It works", Toast.LENGTH_LONG).show()
}
override fun onCreate(savedInstanceState: Bundle?) {
registerReceiver(broadcastReceiver, IntentFilter().apply {
addAction(Intent.ACTION_PACKAGE_ADDED)
addAction(Intent.ACTION_PACKAGE_REMOVED)
addDataScheme("package") // I could not find a constant for that :(
})
}
override fun onDestroy() {
super.onDestroy()
unregisterReceiver(broadcastReceiver)
}
}
来源:https://stackoverflow.com/questions/51669361/broadcastreceiver-intent-action-package-added-removed-android-oreo