Android8.0 등록 브로드캐스트 잘못된 문제 해결 방법

Android 8.0 이후에는 브로드캐스팅 등록 시 패키지명, 클래스명을 지정해야 하는데, 이전 방법으로 등록 시에도 여전히 브로드캐스팅 수신이 되지 않는 경우

8.0 이전 방송을 등록하는 방법을 살펴보겠습니다.

먼저 방송 수신 클래스를 만듭니다.

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

이 브로드캐스트를 매니페스트 파일에 등록하세요.

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

그런 다음 방송을 보내야 할 곳을 적어주세요

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

브로드캐스트 전송을 실행하면 브로드캐스트 리시버에서 정보를 받게 되지만 Android 8.0 이후부터는 달라집니다. 처음 두 코드는 이동할 필요가 없으며 전송 시 패키지 이름과 클래스 이름만 지정하면 됩니다.

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

판단을 추가하다

    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);
    }

 

추천

출처blog.csdn.net/lanrenxiaowen/article/details/113634320