Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register for ACTION_PACKAGE_ADDED and ACTION_PACKAGE_REMOVED on Android Oreo?

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_REMOVED is not among them. Is there a workaround for receiving these broadcasts?

like image 574
Shubham Avatar asked Sep 01 '17 08:09

Shubham


2 Answers

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().

like image 60
Tim Avatar answered Sep 28 '22 01:09

Tim


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)
    }
}
like image 39
Nivaldo Bondança Avatar answered Sep 28 '22 01:09

Nivaldo Bondança