Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use implicit broadcast PACKAGE_ADDED in Oreo (8.0)?

I have to receive system-sent implicit broadcasts (ACTION_PACKAGE_ADDED) to detect the installation of the application and perform some code. I used the code below:

public class Receiver extends BroadcastReceiver{
   @Override
   public void onReceive(Context context, Intent intent) {
     // It will trigger when any app is installed           
        Uri data = intent.getData();
        String packageAdv = data.getEncodedSchemeSpecificPart();
     //some code...
   }
}

In my Manifest file I declared my receiver:

<receiver android:name="com.myapp.Receiver">
        <intent-filter>                    
           <action android:name="android.intent.action.PACKAGE_ADDED" />                        
           <data android:scheme="package"/> 
        </intent-filter>
</receiver> 

It works perfect before Version 8.0 Oreo. Now, I have to make my receiver explicit by using registerReceiver. How can I do this? Sample code would be appreciated.

like image 286
Nolesh Avatar asked Mar 19 '18 12:03

Nolesh


People also ask

What is implicit broadcast?

An implicit broadcast is one that does not target your application specifically so it is not exclusive to your application. To register for one, you need to use an IntentFilter and declare it in your manifest.

How broadcast receiver works in Android?

Android BroadcastReceiver is a dormant component of android that listens to system-wide broadcast events or intents. When any of these events occur it brings the application into action by either creating a status bar notification or performing a task.


1 Answers

I have decided to create a simple service for listening to PACKAGE_ADDED event.

public class MyService extends Service {
  private BroadcastReceiver receiver;

  public MyService() { }

  @Override
  public void onCreate() {
    IntentFilter intentFilter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
    intentFilter.addDataScheme("package");
    receiver = new Receiver();
    registerReceiver(receiver, intentFilter);
  }

  //ensure that we unregister the receiver once it's done.
  @Override
  public void onDestroy() {
    unregisterReceiver(receiver);
  }

  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }

}

Also, I needed to declare my service in manifest file:

<service
    android:name="com.nolesh.myapp.MyService"
    android:enabled="true">
</service>
like image 192
Nolesh Avatar answered Oct 13 '22 01:10

Nolesh