Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

android - Receiving package install and uninstall events

I am trying to detect when a new App is being installed but only if my app is running. I managed to detect the installation of the app by making a BroadcastReceiver and activating it inside the AndroidManifest file but this will detect even if my app is closed. So that is why I need to manually activate and deactivate the broadcastreveiver. To do this I have this code:

br = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        Log.i("Enter", "Enters here");
        Toast.makeText(context, "App Installed!!!!.", Toast.LENGTH_LONG).show();
    }
};
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
intentFilter.addAction(Intent.ACTION_PACKAGE_INSTALL);
registerReceiver(br, intentFilter);

This should make a toast when a new app is installed. But sadly it does not. It does not enter in the onReceive method. Any help is appreciated.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I tried to register the BroadcastReceiver in either manifest file or java code. But both of these two methods failed to trigger the onReceive() method. After googling this problem, I found a solution for both methods from another Thread in SO: Android Notification App

In the manifest file (this approach no longer applies since API 26 (Android 8), it was causing performance issues on earlier Android versions):

<receiver android:name=".YourReceiver">
    <intent-filter>
        <action android:name="android.intent.action.PACKAGE_INSTALL" />
        <action android:name="android.intent.action.PACKAGE_ADDED" />
        <data android:scheme="package"/>
    </intent-filter>
</receiver>

In java code:

IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
intentFilter.addAction(Intent.ACTION_PACKAGE_INSTALL);
intentFilter.addDataScheme("package");
registerReceiver(br, intentFilter);

This should work for you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...