下面列出了android.app.job.JobScheduler#RESULT_SUCCESS 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void scheduleRefresh() {
int cycleTime;
long delta = (new Date().getTime() - mCurrentActivityStartTime.getTime() + 500) / 1000;
if(delta <= 15) {
cycleTime = 1000 * 10;
}else if(delta <= 45){
cycleTime = 1000 * 20;
}else if(delta <= 95){
cycleTime = 1000 * 60;
}else{
cycleTime = 1000 * 60 * 5; /* 5 min for now. if we want we can make this time configurable in the settings */
}
ComponentName componentName = new ComponentName(ActivityDiaryApplication.getAppContext(), RefreshService.class);
JobInfo.Builder builder = new JobInfo.Builder(ACTIVITY_HELPER_REFRESH_JOB, componentName);
builder.setMinimumLatency(cycleTime);
refreshJobInfo = builder.build();
JobScheduler jobScheduler = (JobScheduler) ActivityDiaryApplication.getAppContext().getSystemService(JOB_SCHEDULER_SERVICE);
int resultCode = jobScheduler.schedule(refreshJobInfo);
if (resultCode != JobScheduler.RESULT_SUCCESS) {
Log.w(TAG, "RefreshJob not scheduled");
}
// TODO: do we need to keep track on the scheduled jobs, or is a waiting job with the same ID as a new one automatically canceled?
}
private static void registerForNetworkAvailability(Context context) {
JobScheduler jobScheduler = (JobScheduler) context.getSystemService(JOB_SCHEDULER_SERVICE);
if (jobScheduler == null) {
return;
}
int scheduleId = getScheduleId(context, ON_NETWORK_AVAILABLE_JOB_ID);
jobScheduler.cancel(scheduleId);
int r = jobScheduler.schedule(new JobInfo.Builder(scheduleId, new ComponentName(context, MobileMessagingJobService.class))
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.build());
if (r == JobScheduler.RESULT_SUCCESS) {
MobileMessagingLogger.d(TAG, "Registered job for connectivity updates");
} else {
MobileMessagingLogger.e(TAG, "Failed to register job for connectivity updates");
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
static void scheduleJob(Context context, Bundle extras) {
ComponentName jobComponentName = new ComponentName(context.getPackageName(), GcmJobService.class.getName());
JobScheduler mJobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
JobInfo existingInfo = mJobScheduler.getPendingJob(JOB_ID);
if (existingInfo != null) {
mJobScheduler.cancel(JOB_ID);
}
JobInfo.Builder jobBuilder = new JobInfo.Builder(JOB_ID, jobComponentName)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY).setTransientExtras(extras);
int result = mJobScheduler.schedule(jobBuilder.build());
if (result != JobScheduler.RESULT_SUCCESS) {
Log.e(LCAT, "Could not start job, error code: " + result);
}
}
private static void scheduleJob(Context context) {
JobScheduler scheduler =
(JobScheduler)context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
JobInfo info = getJobInfo(
preferences.getBoolean("backgroundDownloadRequireUnmetered", true),
preferences.getBoolean("backgroundDownloadAllowRoaming", false),
preferences.getBoolean("backgroundDownloadRequireCharging", false));
LOGGER.info("Scheduling background download job: " + info);
int result = scheduler.schedule(info);
if (result == JobScheduler.RESULT_SUCCESS) {
LOGGER.info("Successfully scheduled background downloads");
} else {
LOGGER.log(Level.WARNING, "Unable to schedule background downloads");
}
}
@Override
public boolean schedule(Context context, TaskInfo taskInfo) {
ThreadUtils.assertOnUiThread();
if (!BackgroundTaskScheduler.hasParameterlessPublicConstructor(
taskInfo.getBackgroundTaskClass())) {
Log.e(TAG, "BackgroundTask " + taskInfo.getBackgroundTaskClass()
+ " has no parameterless public constructor.");
return false;
}
JobInfo jobInfo = createJobInfoFromTaskInfo(context, taskInfo);
JobScheduler jobScheduler =
(JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
if (taskInfo.shouldUpdateCurrent()) {
jobScheduler.cancel(taskInfo.getTaskId());
}
int result = jobScheduler.schedule(jobInfo);
return result == JobScheduler.RESULT_SUCCESS;
}
@Override
public boolean schedule(Requirements requirements, String servicePackage, String serviceAction) {
JobInfo jobInfo =
buildJobInfo(jobId, jobServiceComponentName, requirements, serviceAction, servicePackage);
int result = jobScheduler.schedule(jobInfo);
logd("Scheduling job: " + jobId + " result: " + result);
return result == JobScheduler.RESULT_SUCCESS;
}
@Override
public boolean schedule(Requirements requirements, String servicePackage, String serviceAction) {
JobInfo jobInfo =
buildJobInfo(jobId, jobServiceComponentName, requirements, serviceAction, servicePackage);
int result = jobScheduler.schedule(jobInfo);
logd("Scheduling job: " + jobId + " result: " + result);
return result == JobScheduler.RESULT_SUCCESS;
}
@Override
public boolean schedule(Requirements requirements, String servicePackage, String serviceAction) {
JobInfo jobInfo =
buildJobInfo(jobId, jobServiceComponentName, requirements, serviceAction, servicePackage);
int result = jobScheduler.schedule(jobInfo);
logd("Scheduling job: " + jobId + " result: " + result);
return result == JobScheduler.RESULT_SUCCESS;
}
@Override
public boolean schedule(Requirements requirements, String servicePackage, String serviceAction) {
JobInfo jobInfo =
buildJobInfo(jobId, jobServiceComponentName, requirements, serviceAction, servicePackage);
int result = jobScheduler.schedule(jobInfo);
logd("Scheduling job: " + jobId + " result: " + result);
return result == JobScheduler.RESULT_SUCCESS;
}
@Override
public boolean schedule(Requirements requirements, String servicePackage, String serviceAction) {
JobInfo jobInfo =
buildJobInfo(jobId, jobServiceComponentName, requirements, serviceAction, servicePackage);
int result = jobScheduler.schedule(jobInfo);
logd("Scheduling job: " + jobId + " result: " + result);
return result == JobScheduler.RESULT_SUCCESS;
}
public int scheduleAsPackage(JobInfo job, JobWorkItem work, int uId, String packageName,
int userId, String tag) {
try {
if (ActivityManager.getService().isAppStartModeDisabled(uId,
job.getService().getPackageName())) {
Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
+ " -- package not allowed to start");
return JobScheduler.RESULT_FAILURE;
}
} catch (RemoteException e) {
}
synchronized (mLock) {
final JobStatus toCancel = mJobs.getJobByUidAndJobId(uId, job.getId());
if (work != null && toCancel != null) {
// Fast path: we are adding work to an existing job, and the JobInfo is not
// changing. We can just directly enqueue this work in to the job.
if (toCancel.getJob().equals(job)) {
toCancel.enqueueWorkLocked(ActivityManager.getService(), work);
// If any of work item is enqueued when the source is in the foreground,
// exempt the entire job.
toCancel.maybeAddForegroundExemption(mIsUidActivePredicate);
return JobScheduler.RESULT_SUCCESS;
}
}
JobStatus jobStatus = JobStatus.createFromJobInfo(job, uId, packageName, userId, tag);
// Give exemption if the source is in the foreground just now.
// Note if it's a sync job, this method is called on the handler so it's not exactly
// the state when requestSync() was called, but that should be fine because of the
// 1 minute foreground grace period.
jobStatus.maybeAddForegroundExemption(mIsUidActivePredicate);
if (DEBUG) Slog.d(TAG, "SCHEDULE: " + jobStatus.toShortString());
// Jobs on behalf of others don't apply to the per-app job cap
if (ENFORCE_MAX_JOBS && packageName == null) {
if (mJobs.countJobsForUid(uId) > MAX_JOBS_PER_APP) {
Slog.w(TAG, "Too many jobs for uid " + uId);
throw new IllegalStateException("Apps may not schedule more than "
+ MAX_JOBS_PER_APP + " distinct jobs");
}
}
// This may throw a SecurityException.
jobStatus.prepareLocked(ActivityManager.getService());
if (work != null) {
// If work has been supplied, enqueue it into the new job.
jobStatus.enqueueWorkLocked(ActivityManager.getService(), work);
}
if (toCancel != null) {
// Implicitly replaces the existing job record with the new instance
cancelJobImplLocked(toCancel, jobStatus, "job rescheduled by app");
} else {
startTrackingJobLocked(jobStatus, null);
}
StatsLog.write_non_chained(StatsLog.SCHEDULED_JOB_STATE_CHANGED,
uId, null, jobStatus.getBatteryName(),
StatsLog.SCHEDULED_JOB_STATE_CHANGED__STATE__SCHEDULED,
JobProtoEnums.STOP_REASON_CANCELLED);
// If the job is immediately ready to run, then we can just immediately
// put it in the pending list and try to schedule it. This is especially
// important for jobs with a 0 deadline constraint, since they will happen a fair
// amount, we want to handle them as quickly as possible, and semantically we want to
// make sure we have started holding the wake lock for the job before returning to
// the caller.
// If the job is not yet ready to run, there is nothing more to do -- we are
// now just waiting for one of its controllers to change state and schedule
// the job appropriately.
if (isReadyToBeExecutedLocked(jobStatus)) {
// This is a new job, we can just immediately put it on the pending
// list and try to run it.
mJobPackageTracker.notePending(jobStatus);
addOrderedItem(mPendingJobs, jobStatus, mEnqueueTimeComparator);
maybeRunPendingJobsLocked();
}
}
return JobScheduler.RESULT_SUCCESS;
}
@Override
public int schedule(JobInfo job) {
int result = jobScheduler.schedule(toPlatformJob(job).build());
return result == JobScheduler.RESULT_SUCCESS ? RESULT_SUCCESS : RESULT_FAILURE;
}
protected static String scheduleResultToString(int scheduleResult) {
return scheduleResult == JobScheduler.RESULT_SUCCESS ? "success" : "failure";
}