如果你看到這篇文章 相信你已經(jīng)在適配8.0 各種莫名其妙的bug苦惱
筆者在適配8.0發(fā)現(xiàn),xml注冊的靜態(tài)廣播無法接收
先說明問題出現(xiàn)的根本原因
google官方文檔
https://developer.android.com/guide/components/broadcasts.html#receiving_broadcasts
Beginning with Android 8.0 (API level 26), the system imposes additional restrictions on manifest-declared receivers.
If your app targets API level 26 or higher, you cannot use the manifest to declare a receiver for most implicit broadcasts (broadcasts that do not target your app specifically).
解釋一下
在Android 8.0 及以上 在xml中注冊的廣播,在接收的時候收到了額外的限制,如果你的app目標等級是26及以上,將無法接收到xml注冊的廣播
這是google 為了app注冊的靜態(tài)廣播導(dǎo)致耗電加的限制
既然google已經(jīng)都這么規(guī)定了,想反抗是萬萬不能的,但是解決辦法還是有的
辦法一:
使用動態(tài)廣播registerReceiver注冊形式,這個不受限制(推薦)
辦法二:
gradle 中的targetSdkVersion 設(shè)置小于26
附上 查詢已經(jīng)注冊的Receiver code
PackageManager pm = getPackageManager();
List<ResolveInfo> resolveInfos = pm.queryBroadcastReceivers(intent, 0);
for (int i = 0; i < resolveInfos.size(); i++) {
Log.e("resolveInfos","resolveInfos---"+resolveInfos.get(i).toString());
}
更新一波,一種靜態(tài)注冊可行辦法
指定broadcast 接收
Intent intent = new Intent();
intent.setAction("test");
intent.setComponent(new ComponentName(MainActivity.this, MyBroadcastReceiver.class));
sendBroadcast(intent);
接收代碼
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.e("action", action + "");
}
最后xml靜態(tài)注冊
<receiver android:name=".MyBroadcastReceiver"></receiver>
這種方式 可以靜態(tài)的指定的BroadcastReceiver接收 ..