Not allowed to start service Intent - Android Oreo

后端 未结 2 479
轮回少年
轮回少年 2021-01-06 05:36

I am currently using the startWakefulService function which is crashing in Oreo. I realise I either have to switch to startForegroundService() and use a foreground service,

2条回答
  •  甜味超标
    2021-01-06 06:21

    Based on the documentation:

    As of Android O, background check restrictions make this class no longer generally useful. (It is generally not safe to start a service from the receipt of a broadcast, because you don't have any guarantees that your app is in the foreground at this point and thus allowed to do so.) Instead, developers should use android.app.job.JobScheduler to schedule a job, and this does not require that the app hold a wake lock while doing so (the system will take care of holding a wake lock for the job).

    Only alternative is to start a ForeGroundService or use JobScheduler/JobIntentService

    You can start foreground service as follows:

    @Override
    public void onReceive(Context context, Intent intent) {
    
        // Explicitly specify that GCMIntentService will handle the intent.
        ComponentName comp = new ComponentName(context.getPackageName(), GCMIntentService.class.getName());
        // Start the service, keeping the device awake while it is launching.
        ContextCompat.startForegroundService(context,intent.setComponent(comp));
        ...
    }
    

    You also need to call startService() from your Service class and display notification. You can follow my answer on this SO for implementation details.

提交回复
热议问题