Android-BroadcastReceiver 监听问题

Android-BroadcastReceiver 监听问题

清晨说ぺ晚安 发布于 2017-03-14 字数 426 浏览 1124 回复 1

我注册了这样一个Receive,但是监听不倒是什么原因:

private void registerReceiver() {
receiver = new installReceiver(appid);
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_PACKAGE_ADDED);
filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
this.registerReceiver(receiver, filter);
}

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

虐人心 2017-05-01 1 楼

贴一份简单的实例:

public class PackageBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();

if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
// [Neo] TODO
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
// [Neo] TODO
} else if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
// [Neo] TODO
}
}
};

注册部分:

receiver = new PackageBroadcastReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_PACKAGE_ADDED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
filter.addDataScheme("package");

registerReceiver(receiver, filter);

如果还是没有收到数据,请尝试在 AndroidMainfest 中添加如下内容:
但是这样子的话,广播一旦注册上便不再受 Activity 注销控制,除了 System.exit 或者杀死进程,广播将会由系统来接管和关闭。

<receiver android:name=".PackageBroadcastReceiver">
<intent-filter>
<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>
</receiver>

请注意两者含有:
filter.addDataScheme("package");
<data android:scheme="package" />

祝好,
斑驳敬上