//下面是我在我的一个项目中使用的代码,它对我来说工作正常。
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void scheduleJob(Context context) {
//https://kb.sos-berlin.com/pages/viewpage.action?pageId=3638048
//Scheduler uses UTC times for all its internal operations. This ensures a continual flow of operation without breaks or repetitions regardless of any changes in local time.
JobInfo.Builder builder = new JobInfo.Builder(JOB_ID, new ComponentName(context, MyService.class));//JobSchedulerService.class.getName()));
builder.setPersisted(true); //persist across device reboots
builder.setPeriodic((120 * 60 * 1000)); //run once after 2 hours seconds
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY); // only if wifi avaiblable so they are not using bandwith
builder.setRequiresDeviceIdle(false); // run not only if the device is idle
builder.setRequiresCharging(false); // run not only if the device is charging
// android.os.PersistableBundle bundle = new android.os.PersistableBundle();
// bundle.putString(WEB_SERVICE_URL, "http://example.com?upload.php");
// builder.setExtras(bundle);
//builder.setBackoffCriteria(1600, JobInfo.BACKOFF_POLICY_LINEAR);
//BACKOFF_POLICY_LINEAR After one failure retry at 1 * your value, then at 2 * (your value), then 3 * (your value) and so on
//BACKOFF_POLICY_EXPONENTIAL After one failure retry at your value, then at (your value)^2, (your value)^3 and so on
//builder.setMinimumLatency(5 * 1000); //latency
//builder.setOverrideDeadline(50 * 1000); //wait for criteria to be met, in 50 seconds if they have not then run anyways
int test = jobScheduler.schedule(builder.build());
if (test <= 0) {
Utility.showDialog(context, "Service Error", "Service is not responding");
//If something goes wrong
}
}
我们按照以下说明定义了服务类别:
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class MyService extends JobService {
@Override
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public boolean onStartJob(final JobParameters params) {
Log.e(TAG, "onStartJob");
String month = "3";
String year = "2018";
MyAsync myAsync = new MyAsync(MyService.this, arraydata, month, year, new SyncAsyncListener() {
@Override
public void onDataSuccess() {
try {
jobFinished(params, result);
} catch (Exception e) {
}
}
});
myAsync.execute();
}
return result;
}
@Override
public boolean onStopJob(JobParameters jobParameters) {
return false;
}
}