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

前端 未结 17 1218
借酒劲吻你
借酒劲吻你 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:34

    If any intent was previously working fine when the app is in the background, it won't be the case any more from Android 8 and above. Only referring to intent which has to do some processing when app is in the background.

    The below steps have to be followed:

    1. Above mentioned intent should be using JobIntentService instead of IntentService.
    2. The class which extends JobIntentService should implement the - onHandleWork(@NonNull Intent intent) method and should have below the method, which will invoke the onHandleWork method:

      public static void enqueueWork(Context context, Intent work) {
          enqueueWork(context, xyz.class, 123, work);
      }
      
    3. Call enqueueWork(Context, intent) from the class where your intent is defined.

      Sample code:

      Public class A {
      ...
      ...
          Intent intent = new Intent(Context, B.class);
          //startService(intent); 
          B.enqueueWork(Context, intent);
      }
      

    The below class was previously extending the Service class

    Public Class B extends JobIntentService{
    ...
    
        public static void enqueueWork(Context context, Intent work) {
            enqueueWork(context, B.class, JobId, work);
        }
    
        protected void onHandleWork(@NonNull Intent intent) {
            ...
            ...
        }
    }
    
    1. com.android.support:support-compat is needed for JobIntentService - I use 26.1.0 V.

    2. Most important is to ensure the Firebase libraries version is on at least 10.2.1, I had issues with 10.2.0 - if you have any!

    3. Your manifest should have the below permission for the Service class:

      service android:name=".B"
      android:exported="false"
      android:permission="android.permission.BIND_JOB_SERVICE"
      

    Hope this helps.

提交回复
热议问题