How to detect new apps in an Android device

android, android-package-managers, broadcastreceiver, contentobserver

Solution

You can register a `BroadcastReceiver` using `Intent.ACTION_PACKAGE_ADDED` (and also `Intent.ACTION_PACKAGE_REMOVED` and/or `Intent.ACTION_PACKAGE_CHANGED` if necessary). For instance,

void registerReceiver() {
    IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
    filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
    filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
    filter.addDataScheme("package_name");     
}

public void onReceive(Context context, Intent intent) {
    final String action = intent.getAction();

    if (action.equals(Intent.ACTION_PACKAGE_ADDED)) {
        Uri data = intent.getData();
        String pkgName = data.getEncodedSchemeSpecificPart();
    }

    /* etc. */
}

Problem

I want to detect when the user installs or deletes an app, and I didn't find a `BroadcastReceiver` that does this. In my app, I get the information about the installed apps with the class `PackageManager`, but I don't want to scan the apps periodically. Is there any `BroadcastReceiver` that does this? Or any `ContentObserver`? Is it possible to get a notification that an app has been installed or removed?

Original source