3

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?

Charles
  • 50,943
  • 13
  • 104
  • 142
Alexrs95
  • 392
  • 1
  • 3
  • 13
  • I believe the answer is _no_ ... – Kristopher Micinski Jul 14 '12 at 22:20
  • It appears I was wrong, :-), I had forgotten that one! – Kristopher Micinski Jul 14 '12 at 22:27
  • If you are feeling ambitious, you should take a look at the `AsyncTaskLoader` class... implementing your own `Loader` here would be a damn good learning experience in my opinion :P – Alex Lockwood Jul 14 '12 at 22:30
  • 1
    The [**sample code**](http://developer.android.com/reference/android/content/AsyncTaskLoader.html) in the docs actually does exactly what you describe (or at least I believe it does, from the looks of it). Check it out! – Alex Lockwood Jul 14 '12 at 22:31
  • Thank you for all. I don't know how I will do it, but I want to upload the data to a server when the app list change, without requiring the app be running at that moment, so I think I will do it with a service, Is it the best way to do? :) – Alexrs95 Jul 14 '12 at 23:00

1 Answers1

8

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. */
}
Alex Lockwood
  • 83,063
  • 39
  • 206
  • 250
  • I think that `Intent.ACTION_PACKAGE_CHANGED` do the same that `Intent.ACTION_PACKAGE_ADDED` and `Intent.ACTION_PACKAGE_REMOVED`, no? – Alexrs95 Jul 14 '12 at 23:13
  • No. You can check from this: http://developer.android.com/reference/android/content/Intent.html#ACTION_PACKAGE_ADDED – trante Nov 12 '13 at 20:02
  • Thanks I was looking for 'getEncodedSchemeSpecificPart' I had expected it to be getHost I needed but the lack of // in the uri broke that... – Nathan Schwermann Mar 07 '14 at 17:52