满足 DeadLine 约束条件的 Job 基本会被立即执行,无论别的约束条件是否满足
满足 Time 约束条件后,Job 基本会被移除
该 Controller 中把 Job 移除,并不会使 Job 的周期执行受到影响;周期性起作用的逻辑在 JobServiceContext 中
一、调用流程
public JobSchedulerService(Context context) {
super(context);
// Create the controllers.
mControllers = new ArrayList();
mControllers.add(ConnectivityController.get(this));
mControllers.add(TimeController.get(this));
mControllers.add(IdleController.get(this));
mControllers.add(BatteryController.get(this));
mHandler = new JobSchedulerService.JobHandler(context.getMainLooper());
mJobSchedulerStub = new JobSchedulerService.JobSchedulerStub();
mJobs = JobStore.initAndGet(this);
}
|
public static synchronized TimeController get(JobSchedulerService jms) {
if (mSingleton == null) {
mSingleton = new TimeController(jms, jms.getContext());
}
return mSingleton;
}
|
private TimeController(StateChangedListener stateChangedListener, Context context) {
super(stateChangedListener, context);
mDeadlineExpiredAlarmIntent = PendingIntent.getBroadcast(mContext, 0 /* ignored */,
new Intent(ACTION_JOB_EXPIRED), 0);
mNextDelayExpiredAlarmIntent = PendingIntent.getBroadcast(mContext, 0 /* ignored */,
new Intent(ACTION_JOB_DELAY_EXPIRED), 0);
mNextJobExpiredElapsedMillis = Long.MAX_VALUE;
mNextDelayExpiredElapsedMillis = Long.MAX_VALUE;
// Register BR for these intents. 注册广播接收器
IntentFilter intentFilter = new IntentFilter(ACTION_JOB_EXPIRED);
intentFilter.addAction(ACTION_JOB_DELAY_EXPIRED);
mContext.registerReceiver(mAlarmExpiredReceiver, intentFilter);
}
二、添加需要追踪的 Job
public synchronized void maybeStartTrackingJob(JobStatus job) {
if (job.hasTimingDelayConstraint() || job.hasDeadlineConstraint()) {
// 首先移除旧 Job
maybeStopTrackingJob(job);
// mTrackedJobs sorted asc. by deadline
ListIterator it = mTrackedJobs.listIterator(mTrackedJobs.size());
while (it.hasPrevious()) {
JobStatus ts = it.previous();
if (ts.getLatestRunTimeElapsed() < job.getLatestRunTimeElapsed()) {
// Insert
break;
}
}
// google 是个坑货,放错位置了
it.add(job);
// 调整 AlarmManager 下次触发时间
maybeUpdateAlarms(
job.hasTimingDelayConstraint() ? job.getEarliestRunTime() : Long.MAX_VALUE,
job.hasDeadlineConstraint() ? job.getLatestRunTimeElapsed() : Long.MAX_VALUE);
}
}
1. 调整最早及最迟可以执行 Job 的时间
private void maybeUpdateAlarms(long delayExpiredElapsed, long deadlineExpiredElapsed) {
if (delayExpiredElapsed < mNextDelayExpiredElapsedMillis) {
setDelayExpiredAlarm(delayExpiredElapsed);
}
if (deadlineExpiredElapsed < mNextJobExpiredElapsedMillis) {
setDeadlineExpiredAlarm(deadlineExpiredElapsed);
}
}
/**
* Set an alarm with the {@link android.app.AlarmManager} for the next time at which a job's
* delay will expire.
* This alarm will not wake up the phone.
*/
private void setDelayExpiredAlarm(long alarmTimeElapsedMillis) {
// 如果 alarmTimeElapsedMillis 已经小于当前时间,则使用当前时间
alarmTimeElapsedMillis = maybeAdjustAlarmTime(alarmTimeElapsedMillis);
mNextDelayExpiredElapsedMillis = alarmTimeElapsedMillis;
updateAlarmWithPendingIntent(mNextDelayExpiredAlarmIntent, mNextDelayExpiredElapsedMillis);
}
/**
* Set an alarm with the {@link android.app.AlarmManager} for the next time at which a job's
* deadline will expire.
* This alarm will wake up the phone.
* 这里注释应该写错了,不会唤醒手机
*/
private void setDeadlineExpiredAlarm(long alarmTimeElapsedMillis) {
// 如果 alarmTimeElapsedMillis 已经小于当前时间,则使用当前时间
alarmTimeElapsedMillis = maybeAdjustAlarmTime(alarmTimeElapsedMillis);
mNextJobExpiredElapsedMillis = alarmTimeElapsedMillis;
updateAlarmWithPendingIntent(mDeadlineExpiredAlarmIntent, mNextJobExpiredElapsedMillis);
}
2. 调整 AlarmManager 触发时间
private void updateAlarmWithPendingIntent(PendingIntent pi, long alarmTimeElapsed) {
ensureAlarmService();
if (alarmTimeElapsed == Long.MAX_VALUE) {
mAlarmService.cancel(pi);
} else {
/**
* This alarm does not wake the device up; if it goes off while the device
* is asleep, it will not be delivered until the next time the device
* wakes up.
* 该闹钟不会唤醒手机
*/
mAlarmService.set(AlarmManager.ELAPSED_REALTIME, alarmTimeElapsed, pi);
}
}
三、移除不再需要追踪的 Job
/**
* When we stop tracking a job, we only need to update our alarms if the job we're no longer
* tracking was the one our alarms were based off of.
* Really an == comparison should be enough, but why play with fate? We'll do <=.
* 注释好搞笑,but, yes, why play with fate!
*/
@Override
public synchronized void maybeStopTrackingJob(JobStatus job) {
if (mTrackedJobs.remove(job)) {
// 查看是否有满足时间约束条件的 Job, 之后触发执行所有满足约束条件的 Job
// 重置 AlarmManager 下次触发时间
checkExpiredDelaysAndResetAlarm();
checkExpiredDeadlinesAndResetAlarm();
}
}
1. 检查满足最早可以执行约束条件的 Job, 重置 AlarmManager 下次触发时间
/**
* Handles alarm that notifies us that a job's delay has expired. Iterates through the list of
* tracked jobs and marks them as ready as appropriate.
*/
private synchronized void checkExpiredDelaysAndResetAlarm() {
final long nowElapsedMillis = SystemClock.elapsedRealtime();
long nextDelayTime = Long.MAX_VALUE;
boolean ready = false;
Iterator it = mTrackedJobs.iterator();
while (it.hasNext()) {
final JobStatus job = it.next();
if (!job.hasTimingDelayConstraint()) {
continue;
}
final long jobDelayTime = job.getEarliestRunTime();
if (jobDelayTime <= nowElapsedMillis) { // 该 Job 满足了该约束条件
job.timeDelayConstraintSatisfied.set(true);
if (canStopTrackingJob(job)) {
// Job 已经满足时间约束条件,不需要再保持追踪. 注意只是从时间追踪队列移除,不影响别的追踪队列
// 此处把 Job 移除,并不会使 Job 的周期执行收到影响;周期性起作用的逻辑在 JobServiceContext 中
it.remove();
}
if (job.isReady()) {
ready = true;
}
} else { // Keep going through list to get next delay time.
if (nextDelayTime > jobDelayTime) {
nextDelayTime = jobDelayTime;
}
}
}
if (ready) {
// 触发 JobSchedulerService 检查所有满足执行条件的 Job,根据策略决定是否放入 mPendingJobs,随后执行 mPendingJobs 中的 Job
mStateChangedListener.onControllerStateChanged();
}
// 重置 AlarmManager 下次触发时间
setDelayExpiredAlarm(nextDelayTime);
}
2. 检查满足最迟需要执行约束条件的 Job 并立即执行, 重置 AlarmManager 下次触发时间
/**
* Checks list of jobs for ones that have an expired deadline, sending them to the JobScheduler
* if so, removing them from this list, and updating the alarm for the next expiry time.
*/
private synchronized void checkExpiredDeadlinesAndResetAlarm() {
long nextExpiryTime = Long.MAX_VALUE;
final long nowElapsedMillis = SystemClock.elapsedRealtime();
Iterator it = mTrackedJobs.iterator();
while (it.hasNext()) {
JobStatus job = it.next();
if (!job.hasDeadlineConstraint()) {
continue;
}
final long jobDeadline = job.getLatestRunTimeElapsed();
if (jobDeadline <= nowElapsedMillis) { // 该 Job 满足了最迟执行约束条件
job.deadlineConstraintSatisfied.set(true);
/**
* 触发 JobSchedulerService 把该 Job 加入 mPendingJobs,
* 并检查所有满足执行条件的 Job 放入 mPendingJobs,随后执行 mPendingJobs 中的 Job
*/
mStateChangedListener.onRunJobNow(job);
// 此处把 Job 移除,并不会使 Job 的周期执行收到影响;周期性起作用的逻辑在 JobServiceContext 中
it.remove();
} else { // Sorted by expiry time, so take the next one and stop.
nextExpiryTime = jobDeadline;
break;
}
}
// 重置 AlarmManager 下次触发时间
setDeadlineExpiredAlarm(nextExpiryTime);
}
3. onRunJobNow(job)执行满足最迟需要执行约束条件的 Job流程
mStateChangedListener.onRunJobNow(job);
|
@Override
public void onRunJobNow(JobStatus jobStatus) {
mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
}
private class JobHandler extends Handler {
@Override
public void handleMessage(Message message) {
switch (message.what) {
case MSG_JOB_EXPIRED:
synchronized (mJobs) {
JobStatus runNow = (JobStatus) message.obj;
// runNow can be null, which is a controller's way of indicating that its
// state is such that all ready jobs should be run immediately.
if (runNow != null && !mPendingJobs.contains(runNow) && mJobs.containsJob(runNow)) {
mPendingJobs.add(runNow);
}
// 检查所有满足执行条件的 Job,放入 mPendingJobs,随后执行
queueReadyJobsForExecutionLockedH();
}
break;
}
// 从 mPendingJobs 中取出 Job 执行
maybeRunPendingJobsH();
// Don't remove JOB_EXPIRED in case one came along while processing the queue.
removeMessages(MSG_CHECK_JOB);
}
}
四、接收到来自 AlarmManager 的广播的执行流程
private final BroadcastReceiver mAlarmExpiredReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// A job has just expired, so we run through the list of jobs that we have and
// notify our StateChangedListener.
if (ACTION_JOB_EXPIRED.equals(intent.getAction())) {
checkExpiredDeadlinesAndResetAlarm();
} else if (ACTION_JOB_DELAY_EXPIRED.equals(intent.getAction())) {
checkExpiredDelaysAndResetAlarm();
}
}
};