我正在构建一个 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);
但是这段代码不起作用,因为服务启动了两次,然后作业没有执行任务。