How can I register a BroadcastReceiver listening for the "PACKAGE_ADDED" action programmatically? I am trying to do something after a package is installed. I can get it working by registering the receiver in the AndroidManifest.xml, but I need to get it working the other way by programmatically registering it so that it only gets called on .apks installed through my app. I've tried it several different ways, the code below is from this answer https://stackoverflow.com/a/4805733/1024722 but it doesn't work. Any ideas?
private BroadcastReceiver receiver;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
ButterKnife.inject(this);
intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.v("test", "received");
}
};
registerReceiver(receiver, intentFilter);
}
EDIT: In my app's activity, I click a button to download the app from the server and then to install it I click the downloaded app in my notification bar. It then presents this screen:
I click "Install" and it installs but doesn't call my onReceive method(unless I register it in the xml). Then it shows this screen:
then I click "done" and it returns to my activity with the "install" button. I am wondering if it's not working because it launches the activities shown in the screenshots, and is therefore not able to call the onReceive method in my receiver since my activity's onPause method has been called and isn't "active" anymore until I click done, which is after the "PACKAGE_ADDED" action gets called.