Android 解决静态广播收不到的问题

最近用到静态广播的时候发现收不到,百度一搜说Android8.0以后加了限制…Emm…

解决办法这里写两个:

1.发送广播的Intent里添加Component参数。
两个参数,一个是包名,一个是receiver所在路径+类名

Intent intent = new Intent("com.example.sendbroadcast.faultmsg");
intent.putExtra("Data", InfoObj.toString());
intent.setComponent(new ComponentName("com.example.sendbroadcast", "com.example.sendbroadcast.receiver.MsgReceiver"));
sendBroadcast(intent);

这种方法虽然好用,但限制颇多,一旦改了包名或者receiver换了文件路径就接收不到了,所以介绍第二种方法。

2.通过action name遍历所有的receiver

Intent intent = new Intent("com.example.sendbroadcast.faultmsg");
PackageManager pm = getPackageManager();
if(null == pm) return;
List<ResolveInfo> broadcastReceivers = pm.queryBroadcastReceivers(intent, 0);
for(int i = 0;i < broadcastReceivers.size(); i++) {
    Log.v("YYYY", "resolveInfos---" + broadcastReceivers.get(i).toString());
    intent.setPackage((broadcastReceivers.get(i).activityInfo.packageName));
    intent.putExtra("Data", InfoObj.toString());
    sendBroadcast(intent);
}

以上~

你可能感兴趣的:(Android)