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

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

我必须接收系统发送的隐式广播 (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> 

Oreo 8.0之前完美运行。现在,我必须使用 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;
  }

}

此外,我需要在 manifest 文件中声明我的服务:

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