Android custom broadcast cannot receive

# Android custom broadcast cannot be received

When I was working on a project recently, I found that since Android 8.0, no matter whether it is a static registration or a dynamic registration custom broadcast, I can’t receive it. Later, I went to Google’s official documentation and found the explanation as follows:

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.

It means that starting from Android 8.0 (API level 26), the system imposes additional restrictions on the receiver declared in the manifest, which can only be received in the application that specifies the package name.

So make the following changes

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


Just use the setComponent() method to specify the application package name and class name to be used.

Guess you like

Origin blog.csdn.net/a307326984/article/details/131116748