Search code examples
androidandroid-8.0-oreoandroid-jobschedulerandroid-8.1-oreo

JobScheduler API crash on Android 8.0 devices


In order to meet Android target API 26 requirements for my app, I modified the background service in my app to be launched with a JobScheduler instead of just as a plain service. Here is my updated code.

In my PhoneUtils class,

 public static void scheduleTTSJob(Context context) {

    if(isTTSJobServiceOn(context))
    {
        return;
    }

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {

        ComponentName serviceComponent = new ComponentName(context, TTSJobScheduledService.class);
        JobInfo.Builder builder = new JobInfo.Builder(JOB_ID, serviceComponent);

        builder.setMinimumLatency(1 * 1000); // wait at least
        builder.setOverrideDeadline(3 * 1000); // maximum delay
        JobScheduler jobScheduler = context.getSystemService(JobScheduler.class);
        jobScheduler.schedule(builder.build());
    }
}

public static boolean isTTSJobServiceOn( Context context ) {

    boolean hasBeenScheduled = false;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

        JobScheduler scheduler = (JobScheduler) context.getSystemService( Context.JOB_SCHEDULER_SERVICE );

        for ( JobInfo jobInfo : scheduler.getAllPendingJobs() ) {
            if ( jobInfo.getId() == JOB_ID ) {
                hasBeenScheduled = true;
                break;
            }
        }
    }

    return hasBeenScheduled;
}

public static void stopTTSJob(Context context)
{
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        JobScheduler scheduler = (JobScheduler) context.getSystemService( Context.JOB_SCHEDULER_SERVICE );

        for ( JobInfo jobInfo : scheduler.getAllPendingJobs() ) {
            if ( jobInfo.getId() == JOB_ID ) {

                scheduler.cancel(JOB_ID);
                break;
            }
        }
    }
}

TTSJobScheduledService class

package services;

import android.annotation.TargetApi;
import android.app.job.JobParameters;
import android.app.job.JobService;
import android.content.Intent;
import android.os.Build;

import utilities.PhoneUtils;

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class TTSJobScheduledService extends JobService {

@Override
public boolean onStartJob(JobParameters params) {
    Intent service = new Intent(getApplicationContext(), TTSService.class);
    getApplicationContext().startService(service);
    PhoneUtils.scheduleTTSJob(getApplicationContext()); // reschedule the job
    return true;
}

@Override
public boolean onStopJob(JobParameters params) {
    return true;
    }
}

Code for TTSService class:

package services;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.speech.tts.TextToSpeech;
import android.support.annotation.Nullable;

public class TTSService extends Service {

   private static TextToSpeech voice =null;

   public static TextToSpeech getVoice() {
    return voice;
}

@Nullable
@Override

public IBinder onBind(Intent intent) {
    // not supporting binding
    return null;
}

public TTSService() {
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    try{

            voice = new TextToSpeech(TTSService.this, new TextToSpeech.OnInitListener() {
                @Override
                public void onInit(final int status) {

                }
            });
    }
    catch(Exception e){
        e.printStackTrace();
    }


    return Service.START_STICKY;
}

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

}

public static void clearTtsEngine()
{
    if(voice!=null)
    {
        voice.stop();
        voice.shutdown();
        voice = null;
    }
}
}

Also, I added this new service in my manifest file:

<service
        android:name="services.TTSJobScheduledService"
        android:label="TTS service"
        android:permission="android.permission.BIND_JOB_SERVICE" >

</service>

I am scheduling this service when user opens my app (if it is not already scheduled), or if device is rebooted, or if app is upgraded on Google Play.

However, soon after I released this app update, I started getting crashes with this stack trace for devices with Android 8.0.0 and above:

Caused by java.lang.IllegalStateException: Not allowed to start service Intent { cmp=abc.fgh.com.abc/services.TTSService }: app is in background uid UidRecord{6dafcbe u0a250 TRNB idle procs:1 seq(0,0,0)}
   at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1505)
   at android.app.ContextImpl.startService(ContextImpl.java:1461)
   at android.content.ContextWrapper.startService(ContextWrapper.java:644)
   at services.TTSJobScheduledService.onStartJob(Unknown Source:15)
   at android.app.job.JobService$1.onStartJob(JobService.java:71)
   at android.app.job.JobServiceEngine$JobHandler.handleMessage(JobServiceEngine.java:108)
   at android.os.Handler.dispatchMessage(Handler.java:105)
   at android.os.Looper.loop(Looper.java:180)
   at android.app.ActivityThread.main(ActivityThread.java:6950)
   at java.lang.reflect.Method.invoke(Method.java)
   at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:835)

As I understand, this should not be happening given that I am using a JobScheduledService scheduleTTSJob() call and not a plain startService() call from my code. It did not crash on device I tested it on (Moto G6), which is also having Android 8.0.0, but is now crashing on these other devices with Android 8.0.0 and above.


Solution

  • As I understand, this should not be happening given that I am using a JobScHeduledService scheduleTTSJob() call and not a plain startService() call from my code

    You are definitely using a plain startService() call from your code. It is in your onStartJob() method:

    @Override
    public boolean onStartJob(JobParameters params) {
        Intent service = new Intent(getApplicationContext(), TTSService.class);
        getApplicationContext().startService(service);
        PhoneUtils.scheduleTTSJob(getApplicationContext()); // reschedule the job
        return true;
    }
    

    and that is where the stack trace shows that you are crashing.

    Please let me know what is the fix to be made in my code

    Either:

    • Delete that startService() call, or

    • Use ContextCompat.startForegroundService() and have TTSService call startForeground() as it starts up, or

    • If applicable, move that TTSService logic into some non-service code in a background thread that you execute directly from onStartJob()

    It is difficult to give you more specific advice, given that we do not know what TTSService is.