How to register for ACTION_PACKAGE_ADDED and ACTION_PACKAGE_REMOVED on Android Oreo?

前端 未结 2 1668
南笙
南笙 2020-12-10 17:13

Looking at the latest Android Oreo release notes, it seems like only a handful of implicit broadcasts can be registered by the apps. ACTION_PACKAGE_ADDED and ACTION_PACKAGE_

相关标签:
2条回答
  • 2020-12-10 17:53

    As posted in https://stackoverflow.com/a/55819091/1848826

    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)
        }
    }
    
    0 讨论(0)
  • 2020-12-10 18:15

    From the docs:

    Apps that target Android 8.0 or higher can no longer register broadcast receivers for implicit broadcasts in their manifest. An implicit broadcast is a broadcast that does not target that app specifically. For example, ACTION_PACKAGE_REPLACED is an implicit broadcast, since it is sent to all registered listeners, letting them know that some package on the device was replaced.

    This says that you cannot register these intents in your manifest. You can still register them programmatically to receive them when your app is running.

    You might also try ACTION_PACKAGE_FULLY_REMOVED, which is one of the exceptions that you can still listen to by registering it in the manifest. There is no such 'alternative' for when a package is added.

    As CW noted, you could also periodically check for changes in the roster of installed apps.

    You can also use polling, setting up a JobScheduler job to check every so often, asking PackageManager for what has changed in the roster of installed apps via getChangedPackages().

    0 讨论(0)
提交回复
热议问题