首页 > 解决方案 > FirebaseJobDispatcher:何时调用 JobService.onStopJob()

问题描述

我已经看到有关此事的问题。检查了源代码,但在完成工作后仍然无法弄清楚为什么JobService.onStopJob() 不被调用

构造的代码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();
}

一个工作安排如下:

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

JobService的还是很简单的,因为我还在尝试测试框架:

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?"
}

onStartJob()调用并且线程开始执行。线程休眠 2 秒,然后jobFinished()被调用。

这不意味着也onStopJob()应该调用它吗?

标签: androidfirebasejob-schedulingfirebase-job-dispatcher

解决方案


如果您阅读 的源代码public abstract class JobService extends Service {,您可以阅读有关何时调用它的所有信息:

/**
   * 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);

这不是一个onJobStopped回调,就像一个动画onComplete,这是一个“嘿,你必须停止”的调用。


推荐阅读