bma*_*vus 20 permissions android broadcastreceiver
我想创建一个可以在安装或删除设备上的其他应用程序时接收广播的应用程序.
我的代码
在表现:
<receiver android:name=".apps.AppListener">
<intent-filter android:priority="100">
<action android:name="android.intent.action.PACKAGE_INSTALL"/>
<action android:name="android.intent.action.PACKAGE_ADDED"/>
<action android:name="android.intent.action.PACKAGE_REMOVED"/>
</intent-filter>
</receiver>
Run Code Online (Sandbox Code Playgroud)
在AppListener中:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class AppListener extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent arg1) {
// TODO Auto-generated method stub
Log.v(TAG, "there is a broadcast");
}
}
Run Code Online (Sandbox Code Playgroud)
但我无法收到任何广播.我认为这个问题是由于应用权限,任何想法?
谢谢你的帮助.
t0m*_*13b 45
在你的清单中:
<receiver android:name=".apps.AppListener">
<intent-filter android:priority="100">
<action android:name="android.intent.action.PACKAGE_INSTALL"/>
<action android:name="android.intent.action.PACKAGE_ADDED"/>
<action android:name="android.intent.action.PACKAGE_REMOVED"/>
</intent-filter>
</receiver>
Run Code Online (Sandbox Code Playgroud)
在intent-filter标记之前添加该行
<data android:scheme="package"/>
Run Code Online (Sandbox Code Playgroud)
所以你的清单应该是这样的:
<receiver android:name=".apps.AppListener">
<intent-filter android:priority="100">
<action android:name="android.intent.action.PACKAGE_INSTALL"/>
<action android:name="android.intent.action.PACKAGE_ADDED"/>
<action android:name="android.intent.action.PACKAGE_REMOVED"/>
<data android:scheme="package"/>
</intent-filter>
</receiver>
Run Code Online (Sandbox Code Playgroud)
我不确定PACKAGE_REMOVED意图,如果它实际可用.
小智 20
您必须消除android.intent.action.PACKAGE_INSTALL,因为它已弃用且不再推荐,因为它仅适用于系统.其他一切都很完美,我建议使用999而不是100,文档没有给出最大或最小数量,数字越大,优先级越高,你的接收者就会有这个意图.对不起翻译.我用西班牙语说和写. 信息
<receiver android:name=".apps.AppListener">
<intent-filter android:priority="999">
<action android:name="android.intent.action.PACKAGE_ADDED"/>
<action android:name="android.intent.action.PACKAGE_REMOVED"/>
<data android:scheme="package"/>
</intent-filter>
Run Code Online (Sandbox Code Playgroud)
伟大的答案,只剩下一件小事:
在每次App更新时,首先调用ACTION_PACKAGE_REMOVED,然后调用ACTION_PACKAGE_ADDED-如果您想忽略这些事件,只需将其添加到onReceive():
if(!(intent.getExtras() != null &&
intent.getExtras().containsKey(Intent.EXTRA_REPLACING) &&
intent.getExtras().getBoolean(Intent.EXTRA_REPLACING, false))) {
//DO YOUR THING
}
Run Code Online (Sandbox Code Playgroud)
这是来自文档:
EXTRA_REPLACING在API级别3中添加字符串EXTRA_REPLACING在ACTION_PACKAGE_REMOVED意图中用作布尔额外字段以指示这是包的替换,因此此广播将立即跟随针对同一包的不同版本的添加广播.常量值:"android.intent.extra.REPLACING"