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

java.lang.RuntimeException: Unable to start receiver com.myapp.alarm.AlarmReceiver: java.lang.IllegalStateException: Not allowed to start service Intent { cmp=com..myapp/.alarm.AlarmSchedulingService (has extras) }: app is in background uid UidRecord{6603235 u0a81 RCVR bg:+2m0s921ms idle change:uncached procs:1 seq(0,0,0)}
IntentService is a service with more Background Execution Limits targeting Android 8.0 and higher. Android Oreo background services has introduces new Background Service Limitations. Many apps with Android Oreo that uses IntentService do not work properly.
So, to implement the same background service functionality for Android Oreo we go with JobIntentService. JobIntentService class introduces in Android Support Library 26.1.0, has same functionality as IntentService. JobIntentService when running on Android oreo and higher versions uses jobs instead of services.
For more visit Background Execution Limits

Below is the implementation of Android 8.0 JobIntentService instead of InentService example and how to use it.
# Use AlarmSchedulingService(JobIntentService class) in class AlarmManager which extends WakefulBroadcastReceiver
Intent intent= new Intent(context, AlarmSchedulingService.class);

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
 enqueueWork(context, AlarmSchedulingService.class, JOB_ID, intent);
}else{
startWakefulService(context, intent);
}

# AlarmSchedulingService.java (JobIntentService class)
//Implementation of a JobIntentService Example.
public class AlarmSchedulingService extends JobIntentService {
    //Unique job ID
    static final int JOB_ID = 1000;

    //a method to enqueue work in to this service.
    static void enqueueWork(Context context, Intent work) {
        enqueueWork(context, AlarmSchedulingService .class, JOB_ID, work);
    }

    //Handles the intent
    @Override
    protected void onHandleWork(Intent intent) {
       // We have received work to do.
       // The system already holding a wake lock at this point.
// your task code  (or function call)
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}


#Old Intent service code for Android version lower than Oreo
public class AlarmSchedulingService extends IntentService {

public AlarmSchedulingService() {
        super("AlarmSchedulingService");
    }

@Override
    protected void onHandleIntent(Intent intent) {
// your task code  (or function call)
    } }

#Use AlarmSchedulingService in class AlarmManager which extends WakefulBroadcastReceiver
Intent service = new Intent(context, AlarmSchedulingService.class);
startWakefulService(context, service);

No comments:

Post a Comment

Popular Posts