首先,我创建了一个空体BroadcastReceiver
。然后,我将它添加到AndroidManifest.xml。但我发现清单中声明的BroadcastReceiver
没有收到任何广播。我通过
sendOrderedBroadcast(new Intent("com.example.action"), null)
或
adb shell am broadcast -a com.example.action
这两种方法都可以在Android 7上运行,但在Android 8上不起作用。但是,如果BroadcastReceiver
是通过registerReceiver
声明的,那么它仍然可以接收广播。
另一方面,android.hardware.usb.action.USB_DEVICE_ATTACHED
适用于Android 7和8。
我想问为什么会这样?我已经在模拟器和物理设备中测试过它。他们有相同的行为。
的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>
...
答案 0 :(得分:3)
作为Android 8.0(API级别26)后台执行限制的一部分,针对API级别26或更高级别的应用程序无法再在其清单中为隐式广播注册广播接收器。
答案 1 :(得分:0)
基于清单的广播适用于Android 8
android的广播限制并不适用于清单中仍然可以注册的所有广播。但是请检查最新的文档,因为这些文档可能取决于Android版本。
<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" />