Android自定义广播无法接收

# Android自定义广播无法接收

最近在做项目时,发现从Android8.0以后,不管是静态注册还是动态注册的自定义广播,始终无法接收到,后来去翻了一下谷歌的官方文档,找到的解释是这样的:

Broadcasts overview

> Android 8.0
Beginning with Android 8.0 (API level 26), the system imposes additional restrictions on manifest-declared receivers.
If your app targets Android 8.0 or higher, you cannot use the manifest to declare a receiver for most implicit broadcasts (broadcasts that don't target your app specifically). You can still use a context-registered receiver when the user is actively using your app.

意思是从 Android 8.0(API 级别 26)开始,系统对清单声明的接收器施加了额外的限制,只能在指定了包名的应用中才能收到。

于是做如下修改

    Button button = (Button) findViewById(R.id.button);
    button.setonClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent=new Intent("com.example.broadcasttest.BROADCAST_TEST");
                //加入下面这一行
                intent.setComponent(new ComponentName(getPackageName(),"com.example.broadcasttest.MybroadcastReceiver"));
                sendbroadcast(intent);
        }
    });


只需要使用 setComponent() 方法指定将要作用的应用包名和类名即可。

猜你喜欢

转载自blog.csdn.net/a307326984/article/details/131116748