Manifest-declared broadcast receiver does not receive custom broadcast on Android 8

Viewed 2780

First, I created a BroadcastReceiver with empty body. Then, I added it to the AndroidManifest.xml. But I found out that BroadcastReceiver declared in manifest does not receive any broadcast. I sent broadcast by

sendOrderedBroadcast(new Intent("com.example.action"), null)

or

adb shell am broadcast -a com.example.action

Both methods works on Android 7 but it does not work on Android 8. However, if the BroadcastReceiver is declared through registerReceiver, then it can still receive the broadcast.

On the other hand, android.hardware.usb.action.USB_DEVICE_ATTACHED works fine on both Android 7 and 8.

I want to ask why does it happen? I have tested it in both emulator and a physical device. They have the same behavior.

AndroidManifest.xml

...
<receiver
    android:name=".device.UsbBroadcastReceiver"
    android:exported="true">
    <intent-filter>
        <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
        <action android:name="com.example.action" />
    </intent-filter>
    <meta-data
        android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
        android:resource="@xml/device_filter" />
</receiver>
...
2 Answers

As part of the Android 8.0 (API level 26) Background Execution Limits, apps that target the API level 26 or higher can no longer register broadcast receivers for implicit broadcasts in their manifest.

Read this

Manifest Based broadcast working for me in android 8

Broadcast restriction by android is not applicable for all the broadcasts some can still be registered inside manifest . But do check latest documentation since these may way depending on android version .

 <receiver
            android:name=".UsbReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED" />
            </intent-filter>
            <meta-data
                android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
                android:resource="@xml/device_filter" />
Related