Android 8.0 静态广播无法接收

如果你看到这篇文章 相信你已经在适配8.0 各种莫名其妙的bug苦恼
笔者在适配8.0发现,xml注册的静态广播无法接收

先说明问题出现的根本原因

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注册的静态广播导致耗电加的限制

既然google已经都这么规定了,想反抗是万万不能的,但是解决办法还是有的

办法一:
使用动态广播registerReceiver注册形式,这个不受限制(推荐)
办法二:
gradle 中的targetSdkVersion 设置小于26

附上 查询已经注册的Receiver code

                PackageManager pm = getPackageManager();
                List resolveInfos = pm.queryBroadcastReceivers(intent, 0);
                for (int i = 0; i < resolveInfos.size(); i++) {
                    Log.e("resolveInfos","resolveInfos---"+resolveInfos.get(i).toString());
                }

更新一波,一种静态注册可行办法

指定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静态注册


这种方式 可以静态的指定的BroadcastReceiver接收 ..

你可能感兴趣的:(Android 8.0 静态广播无法接收)