Android8.0 registration broadcast invalid problem solution

After Android 8.0, you need to specify the package name and class name when registering broadcasting. If you still cannot receive broadcasting when registering according to the previous method

Let's take a look at the way to register broadcasts before 8.0

First create a broadcast receiving class

    /**
     * 静态广播接收器执行方法(接收)
     */
    public static class StaticReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e("接收到的广播","------------1"+intent.getStringExtra("msg"));
            //需要更新的内容
        }
    }

Register this broadcast in manifest file

        <!-- 注册自定义静态广播接收器 -->
        <receiver android:name=".fragment.RecheckedInfoFragment$StaticReceiver">
            <intent-filter>
                <action android:name="com.recheckedinfoadapter.recheckedinfoadapterreelectbarrel.staticreceiver" />
            </intent-filter>
        </receiver>

Then write where you need to send the broadcast

    public static final String RECHECKEDACTION = "com.recheckedinfoadapter.recheckedinfoadapterreelectbarrel.staticreceiver";    //静态广播的Action字符串
    Intent intent = new Intent();
    intent.setAction(RECHECKEDACTION);        //设置Action
    intent.putExtra("msg", "发送的广播");    //添加附加信息
    context.sendBroadcast(intent);

Executing sending a broadcast will receive the information in the broadcast receiver, but it is different after Android 8.0. The first two pieces of code do not need to be moved, just specify the package name and class name when sending

    //context就是当前的类名
    Intent intent = new Intent();
    intent.setAction(RECHECKEDACTION);        //设置Action
    intent.setComponent(new ComponentName(context,    RecheckedInfoFragment.StaticReceiver.class));
    context.sendBroadcast(intent);

add a judgment

    if (Build.VERSION.SDK_INT >= 26) {
        Intent intent = new Intent();
        intent.setAction(RECHECKEDACTION);        //设置Action
        intent.setComponent(new ComponentName(context, RecheckedInfoFragment.StaticReceiver.class));
        context.sendBroadcast(intent);
    }else {
        Intent intent = new Intent();
        intent.setAction(RECHECKEDACTION);        //设置Action
        intent.putExtra("msg", "重选泡药桶成功");    //添加附加信息
        context.sendBroadcast(intent);
    }

 

Guess you like

Origin blog.csdn.net/lanrenxiaowen/article/details/113634320