FirebaseJobDispatcher: When is JobService.onStopJob() called

161 Views Asked by At

I've seen questions on the matter. Checked out the source code but still can't figure out why JobService.onStopJob() is not called, after a job was done.

Code which constructs the Job:

private Job jobFrom(Bundle bundle, int windowStart, int windowEnd) {
   return dispatcher.newJobBuilder()
      .setService(AttackJobService.class)
      .setTag(attack.getPushId())
      .setRecurring(false)
      .setLifetime(Lifetime.UNTIL_NEXT_BOOT)
      .setTrigger(Trigger.executionWindow(windowStart, windowEnd))
      .setReplaceCurrent(false)
      .setExtras(bundle)
      .build();
}

A job is scheduled like bellow:

FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context));
dispatcher.mustSchedule(job);

My JobService is still quite simple, because I am still trying to test the framework:

public boolean onStartJob(@NonNull JobParameters job) {
    new Thread(() -> {
        try {
            Thread.sleep(2000);
            jobFinished(job,false); //signal that the job is done
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }).start();
    return true; // Answers to the question: "Is there still work going on?"
}

public boolean onStopJob(@NonNull JobParameters job) {
    Log.d(TAG, "onStopJob() called");
    return false; // Answers to the question: "Should this job be retried?"
}

The onStartJob() is getting called and the thread starts executing. The thread is sleeping for 2 seconds and then jobFinished() is called.

Doesn't that means that onStopJob() should be called too?

1

There are 1 best solutions below

0
Martin Marconcini On

If you read the Source code for public abstract class JobService extends Service {, you can read all about when it's called:

/**
   * Called when the scheduling engine has decided to interrupt the execution of a running job, most
   * likely because the runtime constraints associated with the job are no longer satisfied. The job
   * must stop execution.
   *
   * @return true if the job should be retried
   * @see com.firebase.jobdispatcher.JobInvocation.Builder#setRetryStrategy(RetryStrategy)
   * @see RetryStrategy
   */
  @MainThread
  public abstract boolean onStopJob(JobParameters job);

This is not an onJobStopped kinda callback, like an animation onComplete, this is a "hey, you must stop" kinda call.