我试图测试使用JobScheduler在Android API 23上安排后台任务的可靠性,因为我注意到有时它的行为不正常并停止工作。
这是我在SystemManager.java类中安排作业的方式:
public static void scheduleUploadJob(Context context) {
ComponentName componentName = new ComponentName(context, BackgroundUploadJobScheduler.class);
JobInfo info = new JobInfo.Builder(123, componentName)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setPersisted(true)
.setPeriodic(120*60*1000)
.build();
JobScheduler scheduler = (JobScheduler) context.getSystemService(JOB_SCHEDULER_SERVICE);
int resultCode = scheduler.schedule(info);
if (resultCode == JobScheduler.RESULT_SUCCESS) {
Log.d("ScheduleJob()", "Job scheduled successfully!");
} else {
Log.d("ScheduleJob()", "Job scheduled Failed!");
}
}
public class BackgroundUploadJobScheduler extends JobService {
private static final String TAG = "JobSevice";
public static boolean jobCancelled = false;
@Override
public boolean onStartJob(JobParameters params) {
Log.d(TAG, "Events upload Job started");
doBackgroundUploading(params, this);
return true;
}
@Override
public boolean onStopJob(JobParameters params) {
Log.d(TAG, "upload Job cancelled before completion");
jobCancelled = true;
return true;
}
public synchronized void doBackgroundUploading(final JobParameters params, final Context context) {
new Thread(new Runnable() {
@Override
public void run() {
if (jobCancelled) {
return;
}
UploadObject uploadObject= //get it from RoomDB
NetworkManager.upload(context,uploadObject);
}
jobFinished(params, false);
}
}).start();
}
我使用Retrofit在NetworkManager.java类中进行网络调用:
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
if (response.isSuccessful()) {
SystemManager.scheduleEventRecordUploadJob(context);
}else{
SystemManager.scheduleEventRecordUploadJob(context);
}
}
@Override
public void onFailure(Call call, Throwable t) {
SystemManager.scheduleEventRecordUploadJob(context);
}
});
初始化应用程序并进行第一个网络呼叫后,我退出了应用程序,断开了USB连接并关闭了屏幕。我把它留了一夜,然后来检查服务器数据库上的记录以获取结果。
当然,我不打算在真实的应用程序上进行如此繁琐的重复工作。但是,我只是在做一个测试应用程序,以了解JobScheduler和JobService的行为。为什么它突然突然消失,又不重新开始?!