Not allowed to start service Intent - Android Oreo

后端 未结 2 477
轮回少年
轮回少年 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条回答
  •  旧时难觅i
    2021-01-06 06:31

    I experience the same behaviour.

    Why this issue happens?

    Due to the new Background Execution Limits of Android 8 and you should not start services background.

    How I fixed it

    Migrate your GCMIntetService to JobIntentService instead of IntentService.

    Please follow this steps: 1) Add the BIND_JOB_SERVICE permission to your service:

    
    

    2) In your GCMIntentService, instead extending the IntentService, use android.support.v4.app.JobIntentService and override onHandleWork then remove the override in you onHandleIntent.

    public class GCMIntentService extends JobIntentService {
    
        // Service unique ID
        static final int SERVICE_JOB_ID = 50;
    
        // Enqueuing work in to this service.
        public static void enqueueWork(Context context, Intent work) {
            enqueueWork(context, GCMIntentService.class, SERVICE_JOB_ID, work);
        }
    
        @Override
        protected void onHandleWork(@NonNull Intent intent) {
            onHandleIntent(intent);
        }
    
        private void onHandleIntent(Intent intent) {
            //Handling of notification goes here
        }
    }
    

    Then finally, in your GCMBroadcastReceiver, enqueue your GCMIntentService.

    public class GCMBroadcastReceiver extends WakefulBroadcastReceiver {
    
        @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.
            // startWakefulService(context, (intent.setComponent(comp)));
    
            //setResultCode(Activity.RESULT_OK);
    
            GCMIntentService.enqueueWork(context, (intent.setComponent(comp)));
        }
    }
    

    This implementation work for me after we update our target sdk to 27 and I hope it works for you.

提交回复
热议问题