我已经创建了一个广播接收器并注册了它,但是我无法接收到Intent。ACTION_PACKAGE_ADDED事件。
val intentFilter = IntentFilter().apply {
addAction(Intent.ACTION_PACKAGE_ADDED)
addAction(Intent.ACTION_PACKAGE_REMOVED)
addDataScheme("package")
}
intentFilter.priority = 999
val rec = IntentReceiver()
registerReceiver(rec, intentFilter)
这是我的BroadcastReceiver类
class IntentReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
Toast.makeText(context, "TEST TOAST", Toast.LENGTH_LONG).show()
val builder =
NotificationCompat.Builder(context!!, "worker_channel")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("App is installed")
.setPriority(NotificationCompat.PRIORITY_HIGH)
val notificationManager: NotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(4, builder.build())
}}
我没有得到任何事件,但是相同的广播接收器工作的意图,如:
Intent.ACTION_PACKAGE_REMOVED
Intent.ACTION_AIRPLANE_MODE_CHANGED
和我在Logcat PACKAGE_ADDED事件的日志
W/BroadcastQueue: Background execution not allowed: receiving Intent { act=android.intent.action.PACKAGE_ADDED dat=package:com.socialnmobile.dictapps.notepad.color.note flg=0x4000010 (has extras) } to com.google.android.gms/.gass.chimera.PackageChangeBroadcastReceiver
我在android 11和12上测试过,除了Intent之外,其他的Intent都工作得很好。ACTION_PACKAGE_ADDED,我错过了什么或做错了什么?
问题解决了,我不得不为android版本10之后的版本添加查询所有包的权限,不知道为什么在文档中没有提到。
<uses-permission
android:name="android.permission.QUERY_ALL_PACKAGES" />