[英]Registering to Same Receiver Multiple times
For some reason I need to register to same receiver multiple times like one in the Manifest and one time in the code. 出于某种原因,我需要多次注册到相同的接收器,如Manifest中的一个和代码中的一次。 I want to listen package changes even the app is not running but installed. 我想听包更改,即使应用程序没有运行但已安装。
1.In the AndroidManifest.xml 1.在AndroidManifest.xml中
<receiver android:name="PackageChangeReceiver">
<intent-filter>
<action android:name="android.intent.action.PACKAGE_CHANGED" />
<action android:name="android.intent.action.PACKAGE_ADDED" />
<action android:name="android.intent.action.PACKAGE_REMOVED" />
<action android:name="android.intent.action.PACKAGE_REPLACED" />
<data android:scheme="package" />
</intent-filter>
2.Also in the code I register to BroadcastReceiver with the following code snippet in the constructor of. 2.在代码中,我在构造函数中使用以下代码片段注册到BroadcastReceiver。
public PackageChangeReceiver(@ForApplication Context context) {
super();
IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
filter.addDataScheme("package");
context.registerReceiver(this, filter);
}
But somehow Android only receives one of them intermittently sometime it receives both. 但不知何故,只有在收到两者时,Android才会间歇性地接收其中一个。 Is there any doc in the newer versions like a performance improvement in Android OS itself such as only receiving one broadcast although registered to multiple times. 新版本中是否有任何文档,例如Android OS本身的性能改进,例如虽然多次注册但只收到一个广播。 Is it device or OS or version specific thing? 它是设备或操作系统或版本特定的东西吗?
I found the solution. 我找到了解决方案。 Marshmallow doesn't allow multiple registration to same broadcast receiver. 棉花糖不允许多次注册到同一个广播接收器。 But if the OS version is less than or equal to LOLLIPOP_MR1, registering to same broadcast receiver is tolerable. 但如果OS版本小于或等于LOLLIPOP_MR1,则可以容忍注册到同一广播接收器。 But since the Marshmallow(API 23) does not allow that, we can do a performance improvement like that. 但由于Marshmallow(API 23)不允许这样做,我们可以做到这样的性能改进。
private static final boolean REGISTER_DUPLICATE_RECEIVER = VERSION.SDK_INT <= VERSION_CODES.LOLLIPOP_MR1;
if (REGISTER_DUPLICATE_RECEIVER) {
IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
filter.addDataScheme("package");
context.registerReceiver(this, filter);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.