Android 8.0: java.lang.IllegalStateException: Not allowed to start service Intent

前端 未结 17 1217
借酒劲吻你
借酒劲吻你 2020-11-22 09:15

On application launch, app starts the service that should to do some network task. After targeting API level 26, my application fails to start service on Android 8.0 on back

17条回答
  •  野性不改
    2020-11-22 09:35

    The best way is to use JobIntentService which uses the new JobScheduler for Oreo or the old services if not available.

    Declare in your manifest:

    
    

    And in your service you have to replace onHandleIntent with onHandleWork:

    public class YourService extends JobIntentService {
    
        public static final int JOB_ID = 1;
    
        public static void enqueueWork(Context context, Intent work) {
            enqueueWork(context, YourService.class, JOB_ID, work);
        }
    
        @Override
        protected void onHandleWork(@NonNull Intent intent) {
            // your code
        }
    
    }
    

    Then you start your service with:

    YourService.enqueueWork(context, new Intent());
    

提交回复
热议问题