我创建了一个 JobScheduler,以根据日期和时间在我的应用程序中为用户提供一些功能。
但发现工作没有安排在我期望的确切时间。在间隔之后,作业都没有停止。根据我的研究,所有日程安排都取决于setOverrideDeadline
,setMinimumLatency
并且durationToSet
发现启动和停止延迟 30-55 秒,这在每次试验中都不一致。
我已经参考此示例重组了我的应用程序功能
以下是我将根据预期日期时间安排的代码示例。(只列出 SO 的必要步骤)
String startDate = "2018-01-05";
String endDate = "2018-01-05";
String startTime = "11:10"
String endTime = "11:30"
将开始日期与开始时间组合后,将日期时间转换为如下格式。结束日期与结束时间类似。
String dateTimeStart = startDate + " " + startTime;//For start date time
String dateTimeEnd = endDate + " " + endTime;//For end date time
将使用以下逻辑来计算长值作业的开始和结束时间。
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
long timeInMilliseconds = 0;
try {
Date mDate = sdf.parse(dateTimeStart);
timeInMilliseconds = mDate.getTime();
} catch (ParseException e) {
Log.e(TAG, e.toString());
} catch (Exception e) {
Log.e(TAG, e.toString());
}
现在基于此输入,我将使用AtomicInteger为每个作业创建一个唯一 ID,并按如下所示安排作业。
public void scheduleJob(int jobID, long startMillSec,long endMilliSec) {
JobInfo.Builder builder = new JobInfo.Builder(jobID, mServiceComponent);
PersistableBundle extras = new PersistableBundle();
long currTimeMillSec= System.currentTimeMillis();
long minLatency =0;
//if time already crossed start time, then start time is current time itself
if(currTimeMillSec>=startMillSec){
minLatency=0;
}else{
minLatency=startMillSec-currTimeMillSec;
}
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_NONE);
builder.setOverrideDeadline(startMillSec);
builder.setMinimumLatency(minLatency);
builder.setRequiresDeviceIdle(false);
builder.setRequiresCharging(false);
builder.setPersisted(true);
long durationToSet=0;
//if time has passes, keep the delta as the duration, or else keep the full duration received from backend
if(currTimeMillSec>=startMillSec){
durationToSet= endMilliSec-currTimeMillSec;
}else{
durationToSet=endMilliSec-startMillSec;
}
//Set duration for job stopping
extras.putLong("WORK_DURATION_KEY", durationToSet);
builder.setExtras(extras);
JobScheduler tm = (JobScheduler) mContext.getSystemService(Context.JOB_SCHEDULER_SERVICE);
tm.schedule(builder.build());
}
下面是我的 JobService 类
public class AppJobScheduler extends JobService
{
@Override
public boolean onStartJob(final JobParameters params) {
sendMessage(MSG_START, params.getJobId());
long duration = params.getExtras().getLong(WORK_DURATION_KEY);
// Uses a handler to delay the execution of jobFinished().
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
sendMessage(MSG_STOP, params.getJobId());
jobFinished(params, false);
}
}, duration);
return true;
}
@Override
public boolean onStopJob(JobParameters params) {
sendMessage(MSG_STOP, params.getJobId());
return false;
}
private void sendMessage(int messageID, @Nullable Object params) {
Message m = Message.obtain();
m.what = messageID;
m.obj = params;
try {
mActivityMessenger.send(m);
} catch (RemoteException e) {
Log.e(TAG, " Error passing service object back to .");
}
}
}
非常感谢您对此的任何帮助!