如何订阅BOOT_COMPLETED事件?

时间:2019-03-30 14:29:40

标签: android android-8.0-oreo

我要订阅 BOOT_COMPLETED意向操作,该操作表示手机已重启。订阅后,我想安排一些警报。我有一个BroadcastReceiver,它监听BOOT_COMPLETED动作,如果我使用的是Android SDK 25 ,它将被命中/调用。如何使BroadcastReceiver中的代码从Android SDK 26(Oreo)及更高版本执行?

当我在sdk 26上运行代码时,出现错误: system_process W/BroadcastQueue: Background execution not allowed: receiving Intent { act=android.intent.action.BOOT_COMPLETED flg=0x400010 }

我已经在一个更简单的案例中创建了一个 Github存储库 https://github.com/Ferencz8/BootIntent,它确切地显示了在sdk上25项工作正常,而在26项上它们无效的工作。

这是 AndroidManifest.xml 部分:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver
            android:name=".BootReceiver"
            android:exported="false">
            <intent-filter>

                <action android:name="android.intent.action.BOOT_COMPLETED" />

                <action android:name="android.intent.action.QUICKBOOT_POWERON"/>
                <action android:name="android.intent.action.REBOOT"/>
            </intent-filter>
        </receiver>
</application>

BroadcastReceiver

public class BootReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(final Context context, final Intent intent) {
        Log.d(BootReceiver.class.getSimpleName(), "In Boot Receiver");
        Intent mainActivityIntent = new Intent(context, MainActivity.class);
        context.startActivity(mainActivityIntent);
    }
}

我已经尝试过从BroadcastReceiver的OnReceive方法中启动类似ForegroundService的方法,但是没有运气:

@Override
    public void onReceive(final Context context,final  Intent intent) {
        intent.setClass(context, AlarmBootService.class);

        if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(intent);
        }
        else{
            context.startService(intent);
        }
}

除了BOOT_COMPLETED,我还尝试添加其他意图操作:

<action android:name="android.intent.action.QUICKBOOT_POWERON"/>
<action android:name="android.intent.action.REBOOT"/>

为了模拟 BOOT_COMPLETED 操作,我使用了以下命令:

adb shell am broadcast -a android.intent.action.BOOT_COMPLETED

这也是我的第一个问题,因此,如果您对如何更好地描述/表达我的问题有任何反馈意见,请务必告诉:)。

0 个答案:

没有答案