首页 > 解决方案 > Oreo - 未调用启动时的广播接收器(未登录 LogCat)

问题描述

我在启动时遇到了奥利奥和广播接收器的问题。我的方法适用于早期版本的 Android,但对于 Oreo(Huawei P20 Lite with Pie)它不起作用。

Boot Receiver 中的 Log.e 不显示在 LogCat 中,并且 BootService onCreate 中的操作未执行(No Log in log cat)。

引导接收器

public class BootReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e(TAG, "Boot Receiver : Boot Start Service : AlarmNotification");

        if ( Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()) ) {
            Intent myIntent = new Intent(context, BootService.class);

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

我已经在 Manifest 文件中设置了权限

AndroidManifest.xml

        <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

        <receiver android:name=".BootReceiver"
            android:enabled="true"
            android:exported="true"
            android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
            <intent-filter>
                <category android:name="android.intent.category.DEFAULT" />
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.ACTION_BOOT_COMPLETED" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />
                <action android:name="com.htc.intent.action.QUICKBOOT_POWERON" />
            </intent-filter>
        </receiver>
        <service
            android:name=".BootService"
            android:enabled="true"
            android:exported="true">
        </service>

BootService Boot Service 适用于早期版本的 Android

public class BootService extends Service {
    public BootService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //Is fired by the Boot Receiver... on Boot !
        Context context = this;
        Log.e(TAG, "Start Alarm");
        //Do something with the code 
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_NOT_STICKY;
    } 
}

也许我忘记了什么,或者我做错了什么?有人可以帮我解决这个问题吗,我已经从 StackeOverflow 测试了多个解决方案并阅读了文档,但对我来说,这个案例并不是很清楚。

谢谢

标签: javaandroidbroadcastreceiverboot

解决方案


推荐阅读