BroadcastReceiver Intent.ACTION_PACKAGE_ADDED/REMOVED Android 奥利奥

BroadcastReceiver Intent.ACTION_PACKAGE_ADDED/REMOVED Android Oreo

这是我的广播接收器 class 以及它在 main 中的实现。

问题是 onReceive 方法永远不会被调用。

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)
     }
 }

请帮忙。提前致谢。

通常 BroadcastReceiver 需要设置多个步骤。

首先,您是否将接收方传递给清单?

<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>

编辑:请看这个,建议ACTION_PACKAGE_FULLY_REMOVED或JobScheduler

也尝试在模拟器上重新安装该应用程序

我可以用下面的代码让它工作

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)
    }
}