我正在建立一个JobService。此JobService应每5秒启动一次服务。但是如果服务已经运行,我就不应该启动它。现在这是我的JobService:
public class BleJobService extends JobService {
JobParameters params;
DoItTask doIt;
@Override
public boolean onStartJob(JobParameters jobParameters) {
this.params = jobParameters;
Log.d("TestService", "Work to be called from here");
doIt = new DoItTask();
doIt.execute();
return true;
}
@Override
public boolean onStopJob(JobParameters jobParameters) {
Log.d("TestService", "System calling to stop the job here");
if (doIt != null)
doIt.cancel(true);
return false;
}
private class DoItTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPostExecute(Void aVoid) {
Log.d("DoItTask", "Clean up the task here and call jobFinished...");
jobFinished(params, true);
super.onPostExecute(aVoid);
}
@Override
protected Void doInBackground(Void... params) {
Log.d("DoItTask", "Working here...");
startService(new Intent(getApplicationContext(), BlePowerService.class));
return null;
}
}
}
在我的活动中,这是启动JobService的代码:
JobInfo jobInfo;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
jobInfo = new JobInfo.Builder(1, componentName)
.setMinimumLatency(5000)
/*.setExtras(bundle)*/.build();
} else {
jobInfo = new JobInfo.Builder(1, componentName)
.setPeriodic(5000)
/*.setExtras(bundle)*/.build();
}
jobScheduler.schedule(jobInfo);
但是这段代码不起作用,因为Service启动了两次,然后Jobs没有执行任务。