我读过有关Android Oreo后台执行限制的内容,它明确指出BOOT_COMPLETED
广播不受影响,但我在Android Oreo上无法使其工作。
首先,我正在使用SDK 27进行编译。其次,我已在清单文件中声明了接收器:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<receiver
android:name="helpers.StartDetectionAtBoot"
android:label="StartDetectionAtBoot"
android:enabled="true"
android:exported="true">
<intent-filter>
<category android:name="android.intent.category.DEFAULT"/>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED"/>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.QUICKBOOT_POWERON"/>
<!--For HTC devices-->
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
<!--For MIUI devices-->
<action android:name="android.intent.action.REBOOT"/>
</intent-filter>
</receiver>
然后是接收方的实现,它也可以像这样简单:
public class StartDetectionAtBoot extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("test", "test");
Intent intent0 = new Intent( context, ActivityRecognitionService.class );
PendingIntent pendingIntent = PendingIntent.getService(context, 111, intent0, PendingIntent.FLAG_UPDATE_CURRENT);
ActivityRecognitionClient activityRecognitionClient = ActivityRecognition.getClient(context);
activityRecognitionClient.requestActivityUpdates(5000, pendingIntent);
}
}
onReceive
方法在Android Oreo设备/模拟器上未被调用,我会始终收到logcat错误:
W/BroadcastQueue: 后台执行被禁止:接收Intent { act=android.intent.action.BOOT_COMPLETED flg=0x400010 }
阅读其他答案时,他们说在清单中注册显式Intent时会出现一些问题,但这不适用于BOOT_COMPLETED
。
也没有这个能帮到我,因为接收器根本没有被调用。
在运行时注册广播意图可以使其工作(在模拟器上从adb shell触发意图),但我不确定这是正确的做法:
registerReceiver(new StartDetectionAtBoot(), new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
这个有已知的bug吗?