在我的应用程序中,我想检测我的软件包何时被替换,因此我有一个以这种方式启用的接收器:
<receiver
android:name="com.x.y.ApplicationsReceiver"
android:enabled="@bool/is_at_most_api_11" >
<intent-filter>
<action android:name="android.intent.action.PACKAGE_REPLACED" />
<data android:scheme="package" />
</intent-filter>
</receiver>
<receiver
android:name="com.x.y.ApplicationsReceiver"
android:enabled="@bool/is_at_least_api_12" >
<intent-filter>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
</intent-filter>
</receiver>
将我的项目从Eclipse导入Android Studio时,出现以下错误:
Element receiver#com.x.y.ApplicationsReceiver at AndroidManifest.xml duplicated with element declared at AndroidManifest.xml.
我知道如何才能解决这个问题,我需要根据Android API级别为不同的目标过滤器启用接收器吗?
答案 0 :(得分:0)
问题正在发生,因为在AndroidManifest
中添加相同的类两次,以便为不同的Action注册BroadcastReceiver。
通过在单BroadcastReceiver
中添加多个动作来执行此操作:
<receiver
android:name="com.x.y.ApplicationsReceiver"
android:enabled="@bool/is_at_most_api_11" >
<intent-filter>
<action android:name="android.intent.action.PACKAGE_REPLACED" />
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
<data android:scheme="package" />
</intent-filter>
</receiver>
现在onReceive
类的ApplicationsReceiver
方法从Intent获取Action并根据API级别执行想要的操作:
@Override
public void onReceive(Context context,Intent intent) {
String action=intent.getAction();
if(action.equalsIgnoreCase("android.intent.action.MY_PACKAGE_REPLACED")){
// do your code here
}else{
// do your code here
}
}