Firebase JobDispatcher - 计划的作业在设备重新启动时丢失

时间:2017-02-06 05:16:24

标签: android firebase android-jobscheduler firebase-job-dispatcher

我正在使用Firebase-JobDispatcher。如果我保持设备开启,我已经安排了一些工作并且工作正常。但是如果我重新启动我的设备,那么预定的工作不会执行或者它没有&#39重新安排?我使用过setLifetime(Lifetime.FOREVER)。仍然在设备重启时丢失了工作。下面是使用的代码 -

Job myJob = dispatcher.newJobBuilder()
.setService(MyJobService.class)
.setTag("DataSend")
.setRecurring(false)
.setLifetime(Lifetime.FOREVER)
.setTrigger(Trigger.executionWindow(0, 0))
.setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
.setConstraints(Constraint.ON_ANY_NETWORK)
.setExtras(myExtrasBundle)
.build();

3 个答案:

答案 0 :(得分:3)

设置Lifetime.FOREVER后,您已在AndroidManifest.xml文件

中添加以下权限
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

以下是安排工作的代码

Job job = jobDispatcher.newJobBuilder()
    .setService(MyJobService.class)
    .setTrigger(Trigger.executionWindow(windowStartTime, 3600))
    .setTag(PENDING_AUTH_JOB) //identifier for the job
    .setRecurring(false) // should not recur
    .setLifetime(Lifetime.FOREVER) // should persist device reboot
    .setReplaceCurrent(false) // no need to replace previous job
    .setConstraints(Constraint.ON_ANY_NETWORK) // set network availability constraint
    .setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
    .build();
try {
  jobDispatcher.mustSchedule(job);
} catch (FirebaseJobDispatcher.ScheduleFailedException e) {
  if (retryCount-- > 0) {
    scheduleJob(0);
  }
}

要检查的另一件事是不将执行窗口设置为0,0。始终设置windowEnd大于windowStart

答案 1 :(得分:0)

我认为在你的MyJobService中应该返回false,以便在执行后重新安排作业;

  public boolean onStartJob(final com.firebase.jobdispatcher.JobParameters jobParameters) {

        //Offloading work to a new thread.
        new Thread(new Runnable() {
            @Override
            public void run() {
                realm=Realm.getDefaultInstance();

                codeYouWantToRun(jobParameters);
            }
        }).start();

        return true;
    }



 public void codeYouWantToRun(final JobParameters parameters) {
 Log.d(TAG, "completeJob: " + "jobStarted");
//bla bla super code doing its linga linga ling 
                Log.d(TAG, "completeJob: " + "jobFinished");

                    //Tell the framework that the job has completed and doesnot needs to be reschedule. Set jobFinished false so that it can rescheduled on a change of network
                    jobFinished(parameters, false);
    }

答案 2 :(得分:0)

尝试setPersisted(boolean)方法。