如何在Oreo(8.0)中使用隐式广播PACKAGE_ADDED?

我必须接收系统发送的隐式广播(ACTION_PACKAGE_ADDED)来检测应用程序的安装并执行一些代码.我使用下面的代码:

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...
   }
}

在我的Manifest文件中,我声明了我的接收器:

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

它在Version 8.0 Oreo之前完美运行.现在,我必须使用registerReceiver使接收器显式化.我怎样才能做到这一点?示例代码将不胜感激.

最佳答案 我决定创建一个简单的服务来监听PACKAGE_ADDED事件.

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;
  }

}

另外,我需要在清单文件中声明我的服务:

<service
    android:name="com.nolesh.myapp.MyService"
    android:enabled="true">
</service>
点赞