我正在使用 firebase Job Dispatcher 来制作由可用网络触发的定期作业。问题是该服务运行大约 5 分钟,有时甚至更短,然后它就完全停止了。我尝试连接和断开网络,但结果是一样的。
根据我之前收集的信息,如果有可用的网络(wifi),则以下代码应该触发周期性任务,由于后台服务中的优化,该周期不准确,但如果我仍然应该触发它不断连接。但它没有,我仍然连接到 wifi 几个小时并在手机上工作,但服务运行时间不超过 5 分钟。
这就是我按照官方文档实现代码的方式
我已经尝试在 gradle 文件中添加compile 'com.firebase:firebase-jobdispatcher:0.5.2'
和
compile 'com.firebase:firebase-jobdispatcher-with-gcm-dep:0.5.2'
(不是同时)。
工作服务
import com.firebase.jobdispatcher.JobParameters;
import com.firebase.jobdispatcher.JobService;
public class MyJobService extends JobService {
@Override
public boolean onStartJob(JobParameters job) {
// Do some work here
Toast.makeText(this, "The service is triggered now!",
Toast.LENGTH_LONG).show();
return false; // Answers the question: "Is there still work going on?"
}
@Override
public boolean onStopJob(JobParameters job) {
return false; // Answers the question: "Should this job be retried?"
}
}
显现
<service
android:exported="false"
android:name=".MyJobService">
<intent-filter>
<action android:name="com.firebase.jobdispatcher.ACTION_EXECUTE"/>
</intent-filter>
</service>
我已将此添加到我的活动中:
// Create a new dispatcher using the Google Play driver.
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context));
Bundle myExtrasBundle = new Bundle();
myExtrasBundle.putString("some_key", "some_value");
Job myJob = dispatcher.newJobBuilder()
// the JobService that will be called
.setService(MyJobService.class)
// uniquely identifies the job
.setTag("my-unique-tag")
// this is a periodic job
.setRecurring(true)
// persist after device reboot
.setLifetime(Lifetime.FOREVER)
// start between 0 and 10 seconds from now
.setTrigger(Trigger.executionWindow(0, 10))
// don't overwrite an existing job with the same tag
.setReplaceCurrent(false)
// retry with exponential backoff
.setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
// constraints that need to be satisfied for the job to run
.setConstraints(
// only run on an unmetered network
Constraint.ON_UNMETERED_NETWORK,
)
.setExtras(myExtrasBundle)
.build();
dispatcher.mustSchedule(myJob);
我也将它添加到清单中以保持工作:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />