BroadcastReceiver Intent.ACTION_PACKAGE_ADDED / REMOVED Android Oreo

问题描述 投票:2回答:2

这是我的广播接收器类和它的主要实现。

问题是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)
     }
 }

请帮忙。提前致谢。

android kotlin broadcastreceiver intentfilter android-broadcast
2个回答
0
投票

通常,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>

编辑:请看这个post,建议在哪里ACTION_PACKAGE_FULLY_REMOVED或JobScheduler

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


0
投票

我可以使用以下代码

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)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.