Search code examples
androidandroid-intentandroid-service

Can a service receive a package.Added intent


I want to show a notification when a new package is added. and I found the code that the manifest file need! what I can't figure out is how to catch the broadcast inside my service. How can I do that?


Solution

  • You can Register an PACKAGE_INSTALL and PACKAGE_ADDED Receiver for Receiving package install and uninstall events and then Start your Service( i.e IntentService) from onReceive of Broadcast Receiver for Showing notification when a new package is added.

    In Manifest.xml:

    <receiver android:name=".PackageReceiver">
            <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 PackageReceiver :

    public class PackageReceiver extends BroadcastReceiver {
    
       @Override
       public void onReceive(Context context, Intent intent) {
           if (intent.getAction().equals(Intent.PACKAGE_INSTALL)) {
                 //START YOUR SERVICE HERE
            } 
        }
    
    }
    

    OR you can also register an receiver dynamically in your service

    br = new BroadcastReceiver() {
    
            @Override
            public void onReceive(Context context, Intent intent) {
                // TODO Auto-generated method stub
                //SHOW notification here or Start Notification Service
            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
        intentFilter.addAction(Intent.ACTION_PACKAGE_INSTALL);
        intentFilter.addDataScheme("package");
        registerReceiver(br, intentFilter);