下面列出了怎么用android.app.job.JobScheduler的API类实例代码及写法,或者点击链接到github查看源代码。
private void scheduleJob() {
int timeDelay = 2000;
int id = 100;
JobInfo.Builder builder =
new JobInfo.Builder(id, new ComponentName(getApplication(), KeepAliveJobService.class));
if (Build.VERSION.SDK_INT >= 24) {
builder.setMinimumLatency(timeDelay);
builder.setOverrideDeadline(timeDelay);
builder.setMinimumLatency(timeDelay);
builder.setBackoffCriteria(timeDelay, JobInfo.BACKOFF_POLICY_LINEAR);
} else {
builder.setPeriodic(timeDelay);
}
builder.setPersisted(true);
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
builder.setRequiresCharging(false);
JobInfo info = builder.build();
JobScheduler jobScheduler =
(JobScheduler) this.getSystemService(Context.JOB_SCHEDULER_SERVICE);
jobScheduler.cancel(id);
jobScheduler.schedule(info);
}
public static void scheduleJob(Context context) {
QiscusLogger.print(TAG, "scheduleJob: ");
ComponentName componentName = new ComponentName(context, QiscusNetworkCheckerJobService.class);
JobInfo jobInfo = new JobInfo.Builder(STATIC_JOB_ID, componentName)
.setMinimumLatency(TimeUnit.SECONDS.toMillis(5))
.setOverrideDeadline(TimeUnit.SECONDS.toMillis(10))
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setPersisted(true)
.build();
JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
if (jobScheduler != null) {
jobScheduler.schedule(jobInfo);
}
}
/**
* Schedules the TimeZoneUpdateIdler job service to run once.
*
* @param context Context to use to get a job scheduler.
*/
public static void schedule(Context context, long minimumDelayMillis) {
// Request that the JobScheduler tell us when the device falls idle.
JobScheduler jobScheduler =
(JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
// The TimeZoneUpdateIdler will send an intent that will trigger the Receiver.
ComponentName idlerJobServiceName =
new ComponentName(context, TimeZoneUpdateIdler.class);
// We require the device is idle, but also that it is charging to be as non-invasive as
// we can.
JobInfo.Builder jobInfoBuilder =
new JobInfo.Builder(TIME_ZONE_UPDATE_IDLE_JOB_ID, idlerJobServiceName)
.setRequiresDeviceIdle(true)
.setRequiresCharging(true)
.setMinimumLatency(minimumDelayMillis);
Slog.d(TAG, "schedule() called: minimumDelayMillis=" + minimumDelayMillis);
jobScheduler.schedule(jobInfoBuilder.build());
}
public static void syncJob(Context context) {
QiscusLogger.print(TAG, "syncJob...");
ComponentName componentName = new ComponentName(context, QiscusSyncJobService.class);
JobInfo jobInfo = new JobInfo.Builder(STATIC_JOB_ID, componentName)
.setMinimumLatency(QiscusCore.getHeartBeat())
.setOverrideDeadline(QiscusCore.getHeartBeat())
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setPersisted(true)
.build();
JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
if (jobScheduler != null) {
jobScheduler.schedule(jobInfo);
}
}
@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;
}
private void cancelRepeating(PendingIntent pendingIntent, Intent intent) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
JobScheduler jobScheduler = (JobScheduler)
context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
String clazz = intent.getComponent().getClassName();
Integer id = null;
try {
id = (Integer) Class.forName(clazz).getDeclaredField("JOB_ID").get(null);
// only cancel periodic services
if (ServiceScheduler.isScheduled(context, id)) {
jobScheduler.cancel(id);
}
pendingIntent.cancel();
} catch (Exception e) {
logger.error("Error in Cancel ", e);
}
}
else {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
pendingIntent.cancel();
}
}
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 void startRefreshTorUnlockIPs(Context context) {
if (context == null || view == null || view.getFragmentActivity() == null || view.getFragmentActivity().isFinishing()) {
return;
}
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP || refreshPeriodHours == 0) {
TorRefreshIPsWork torRefreshIPsWork = new TorRefreshIPsWork(context, null);
torRefreshIPsWork.refreshIPs();
} else {
ComponentName jobService = new ComponentName(context, GetIPsJobService.class);
JobInfo.Builder getIPsJobBuilder;
getIPsJobBuilder = new JobInfo.Builder(mJobId, jobService);
getIPsJobBuilder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
getIPsJobBuilder.setPeriodic(refreshPeriodHours * 60 * 60 * 1000);
JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
if (jobScheduler != null) {
jobScheduler.schedule(getIPsJobBuilder.build());
}
}
}
private void stopRefreshTorUnlockIPs(Context context) {
if (context == null || modulesStatus == null || !modulesStatus.isRootAvailable()) {
return;
}
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP || refreshPeriodHours == 0) {
return;
}
SharedPreferences shPref = PreferenceManager.getDefaultSharedPreferences(context);
if (shPref.getBoolean("swAutostartTor", false)) return;
JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
if (jobScheduler != null) {
jobScheduler.cancel(mJobId);
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void scheduleNetworkJob() {
JobInfo myJob = new JobInfo.Builder(0, new ComponentName(this, NetworkSchedulerService.class))
.setMinimumLatency(1000)
.setOverrideDeadline(2000)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
.setPersisted(true)
.build();
JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
jobScheduler.schedule(myJob);
myJob = new JobInfo.Builder(0, new ComponentName(this, NetworkSchedulerService.class))
.setMinimumLatency(1000)
.setOverrideDeadline(2000)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_METERED)
.setPersisted(true)
.build();
jobScheduler.schedule(myJob);
}
@Override
public void onCreate() {
super.onCreate();
appendLog(this, TAG,"Default locale:", Resources.getSystem().getConfiguration().locale.getLanguage());
PreferenceManager.getDefaultSharedPreferences(this)
.edit()
.putString(Constants.PREF_OS_LANGUAGE, Resources.getSystem().getConfiguration().locale.getLanguage())
.apply();
LanguageUtil.setLanguage(this, PreferenceUtil.getLanguage(this));
sTheme = PreferenceUtil.getTheme(this);
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M) {
JobScheduler jobScheduler = getSystemService(JobScheduler.class);
appendLog(this, TAG, "scheduleStart at YourLocalWeather");
AppPreference.setLastSensorServicesCheckTimeInMs(this, 0);
jobScheduler.cancelAll();
ComponentName serviceComponent = new ComponentName(this, StartAutoLocationJob.class);
JobInfo.Builder builder = new JobInfo.Builder(StartAutoLocationJob.JOB_ID, serviceComponent);
builder.setMinimumLatency(1 * 1000); // wait at least
builder.setOverrideDeadline(3 * 1000); // maximum delay
jobScheduler.schedule(builder.build());
}
}
private void resendTheIntentInSeveralSeconds(int seconds) {
appendLog(getBaseContext(), TAG, "resendTheIntentInSeveralSeconds:SDK:", Build.VERSION.SDK_INT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ComponentName serviceComponent = new ComponentName(this, UpdateWeatherResendJob.class);
JobInfo.Builder builder = new JobInfo.Builder(UpdateWeatherResendJob.JOB_ID, serviceComponent);
builder.setMinimumLatency(seconds * 1000); // wait at least
builder.setOverrideDeadline((3 + seconds) * 1000); // maximum delay
JobScheduler jobScheduler = getSystemService(JobScheduler.class);
jobScheduler.schedule(builder.build());
appendLog(getBaseContext(), TAG, "resendTheIntentInSeveralSeconds: sent");
} else {
AlarmManager alarmManager = (AlarmManager) getBaseContext().getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(),
0,
new Intent(getBaseContext(), UpdateWeatherService.class),
PendingIntent.FLAG_CANCEL_CURRENT);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + (1000 * seconds), pendingIntent);
}
}
public void scheduleDownload(View view) {
sendNotification();
JobScheduler mScheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
ComponentName componentName = new ComponentName(getApplicationContext(), DownloadService.class.getName());
JobInfo.Builder builder = new JobInfo.Builder(JOB_ID, componentName);
builder.setRequiresCharging(true)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
.setRequiresDeviceIdle(true)
.setPeriodic(TimeUnit.DAYS.toMillis(1));
if (Build.VERSION.SDK_INT > 23) {
builder.setPeriodic(TimeUnit.DAYS.toMillis(1), TimeUnit.MINUTES.toMillis(5));
}
JobInfo jobInfo = builder.build();
if (mScheduler != null) {
mScheduler.schedule(jobInfo);
}
}
@RequiresApi(21)
private void scheduleRegularTests(Context context) {
initializeWithContext(context);
ComponentName serviceComponent = new ComponentName(context, BluetoothTestJob.class);
android.app.job.JobInfo.Builder builder =
new android.app.job.JobInfo.Builder(BluetoothTestJob.getJobId(context), serviceComponent);
builder.setRequiresCharging(false);
builder.setRequiresDeviceIdle(false);
builder.setPeriodic(900000L); // 900 secs is 15 minutes -- the minimum time on Android
builder.setPersisted(true);
PersistableBundle bundle = new PersistableBundle();
bundle.putInt("test_type", this.mTestType);
builder.setExtras(bundle);
JobScheduler jobScheduler = (JobScheduler)
context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
if (jobScheduler != null) {
jobScheduler.schedule(builder.build());
}
}
@Test
@Config(sdk = 21)
public void verifyPeriodicJobRescheduled() throws Exception {
assertThat(manager().getAllJobRequests()).isEmpty();
ContentValues contentValues = new JobRequest.Builder("tag")
.setPeriodic(TimeUnit.HOURS.toMillis(1))
.build()
.toContentValues();
manager().getJobStorage().getDatabase()
.insert(JobStorage.JOB_TABLE_NAME, null, contentValues);
Set<JobRequest> requests = manager().getAllJobRequests();
assertThat(requests).isNotEmpty();
JobScheduler scheduler = (JobScheduler) context().getSystemService(Context.JOB_SCHEDULER_SERVICE);
assertThat(scheduler.getAllPendingJobs()).isEmpty();
int rescheduledJobs = new JobRescheduleService().rescheduleJobs(manager());
assertThat(rescheduledJobs).isEqualTo(1);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private static void listing11_11(Context context) {
JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
ComponentName jobServiceName = new ComponentName(context, BackgroundJobService.class);
// Listing 11-11: Scheduling a job with customized back-off criteria
jobScheduler.schedule(
new JobInfo.Builder(BACKGROUND_UPLOAD_JOB_ID, jobServiceName)
// Require a network connection
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
// Require the device has been idle
.setRequiresDeviceIdle(true)
// Force Job to ignore constraints after 1 day
.setOverrideDeadline(TimeUnit.DAYS.toMillis(1))
// Retry after 30 seconds, with linear back-off
.setBackoffCriteria(30000, JobInfo.BACKOFF_POLICY_LINEAR)
// Reschedule after the device has been rebooted
.setPersisted(true)
.build());
}
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");
}
}
public static void scheduleAddWatchNextRequest(Context context, ClipData clipData) {
JobScheduler scheduler = (JobScheduler) context.getSystemService(JOB_SCHEDULER_SERVICE);
PersistableBundle bundle = new PersistableBundle();
bundle.putString(ID_KEY, clipData.getClipId());
bundle.putString(CONTENT_ID_KEY, clipData.getContentId());
bundle.putLong(DURATION_KEY, clipData.getDuration());
bundle.putLong(PROGRESS_KEY, clipData.getProgress());
bundle.putString(TITLE_KEY, clipData.getTitle());
bundle.putString(DESCRIPTION_KEY, clipData.getDescription());
bundle.putString(CARD_IMAGE_URL_KEY, clipData.getCardImageUrl());
scheduler.schedule(new JobInfo.Builder(1,
new ComponentName(context, AddWatchNextService.class))
.setExtras(bundle)
.build());
}
@Override
public void onReceive(Context context, Intent intent) {
JobScheduler jobScheduler =
(JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
// If there are not pending jobs. Create a sync job and schedule it.
List<JobInfo> pendingJobs = jobScheduler.getAllPendingJobs();
if (pendingJobs.isEmpty()) {
String inputId = context.getSharedPreferences(EpgSyncJobService.PREFERENCE_EPG_SYNC,
Context.MODE_PRIVATE).getString(EpgSyncJobService.BUNDLE_KEY_INPUT_ID, null);
if (inputId != null) {
// Set up periodic sync only when input has set up.
EpgSyncJobService.setUpPeriodicSync(context, inputId,
new ComponentName(context, SampleJobService.class));
}
return;
}
// On L/L-MR1, reschedule the pending jobs.
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1) {
for (JobInfo job : pendingJobs) {
if (job.isPersisted()) {
jobScheduler.schedule(job);
}
}
}
}
@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);
}
}
public static void scheduleFaceRecognitionTranining(Context context){
ComponentName componentNameFaceRecognitionTranining = new ComponentName(context, FaceRecognitionTrainingJobService.class);
JobInfo.Builder builderFaceRecognitionTranining = new JobInfo.Builder(LiteracyApplication.FACE_RECOGNITION_TRAINING_JOB_ID, componentNameFaceRecognitionTranining);
int faceRecognitionTrainingPeriodic = MINUTES_BETWEEN_FACE_RECOGNITION_TRAININGS * 60 * 1000;
builderFaceRecognitionTranining.setPeriodic(faceRecognitionTrainingPeriodic); // Every 15 minutes
JobInfo faceRecognitionTrainingJobInfo = builderFaceRecognitionTranining.build();
JobScheduler jobSchedulerFaceRecognitionTranining = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
jobSchedulerFaceRecognitionTranining.schedule(faceRecognitionTrainingJobInfo);
Log.i(context.getClass().getName(), "FACE_RECOGNITION_TRAINING_JOB with ID " + LiteracyApplication.FACE_RECOGNITION_TRAINING_JOB_ID + " has been scheduled with periodic time = " + faceRecognitionTrainingPeriodic);
}
public void init(final Context context) {
if (LOG_DEBUG) {
Log.d(LOG_TAG, "Initializing refresh scheduler");
}
this.context = context;
cleanupPrefs();
refreshInterval = MimiPrefs.refreshInterval(context);
sequencer.start();
refreshScheduler = (JobScheduler) this.context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
}
@RequiresApi(26)
@Override
public void schedule(long delay, @NonNull List<Constraint> constraints) {
JobInfo.Builder jobInfoBuilder = new JobInfo.Builder(getNextId(), new ComponentName(application, SystemService.class))
.setMinimumLatency(delay)
.setPersisted(true);
for (Constraint constraint : constraints) {
constraint.applyToJobInfo(jobInfoBuilder);
}
Log.i(TAG, "Scheduling a run in " + delay + " ms.");
JobScheduler jobScheduler = application.getSystemService(JobScheduler.class);
jobScheduler.schedule(jobInfoBuilder.build());
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private static boolean isScheduled(Context context, Integer jobId) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
for (JobInfo jobInfo : jobScheduler.getAllPendingJobs()) {
// we only don't allow rescheduling of periodic jobs. jobs for individual
// intents such as events are allowed and can end up queued in the job service queue.
if (jobInfo.getId() == jobId && jobInfo.isPeriodic()) {
return true;
}
}
}
return false;
}
public static void schedule(Context context) {
JobInfo pruneJob = new JobInfo.Builder(JOB_ID, new ComponentName(
context.getPackageName(), PruneInstantAppsJobService.class.getName()))
.setRequiresDeviceIdle(true)
.setPeriodic(PRUNE_INSTANT_APPS_PERIOD_MILLIS)
.build();
JobScheduler jobScheduler = context.getSystemService(JobScheduler.class);
jobScheduler.schedule(pruneJob);
}
public static void schedule(Context context) {
JobScheduler js = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
if (js == null) {
Slog.e(TAG, "Can't collect camera usage stats - no Job Scheduler");
return;
}
js.schedule(new JobInfo.Builder(CAMERA_REPORTING_JOB_ID, sCameraStatsJobServiceName)
.setMinimumLatency(TimeUnit.DAYS.toMillis(1))
.setRequiresDeviceIdle(true)
.build());
}
public static void scheduleJob(Context context) {
ComponentName serviceComponent = new ComponentName(context, TestJobService.class);
JobInfo.Builder builder = new JobInfo.Builder(0, serviceComponent);
builder.setMinimumLatency(1 * 1000); // wait at least
builder.setOverrideDeadline(3 * 1000); // maximum delay
//builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED); // require unmetered network
//builder.setRequiresDeviceIdle(true); // device should be idle
//builder.setRequiresCharging(false); // we don't care if the device is charging or not
JobScheduler jobScheduler = context.getSystemService(JobScheduler.class);
jobScheduler.schedule(builder.build());
}
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Received a notification intent in the NotificationService's receiver.");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
// Android encourages us not to start services directly on N+, so instead we
// schedule a job to handle the notification intent. We use the Android JobScheduler
// rather than GcmNetworkManager or FirebaseJobDispatcher since the JobScheduler
// allows us to execute immediately by setting an override deadline of zero
// milliseconds.
// TODO(crbug.com/685210): UMA to check this does not introduce noticeable latency.
PersistableBundle extras = NotificationJobService.getJobExtrasFromIntent(intent);
JobInfo job =
new JobInfo
.Builder(TaskIds.NOTIFICATION_SERVICE_JOB_ID,
new ComponentName(context, NotificationJobService.class))
.setExtras(extras)
.setOverrideDeadline(0)
.build();
JobScheduler scheduler =
(JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
scheduler.schedule(job);
} else {
// TODO(peter): Do we need to acquire a wake lock here?
intent.setClass(context, NotificationService.class);
context.startService(intent);
}
}
/**
* Executed when user clicks on SCHEDULE JOB.
*/
public void scheduleJob(View v) {
JobInfo.Builder builder = new JobInfo.Builder(mJobId++, mServiceComponent);
String delay = mDelayEditText.getText().toString();
if (!TextUtils.isEmpty(delay)) {
builder.setMinimumLatency(Long.valueOf(delay) * 1000);
}
String deadline = mDeadlineEditText.getText().toString();
if (!TextUtils.isEmpty(deadline)) {
builder.setOverrideDeadline(Long.valueOf(deadline) * 1000);
}
boolean requiresUnmetered = mWiFiConnectivityRadioButton.isChecked();
boolean requiresAnyConnectivity = mAnyConnectivityRadioButton.isChecked();
if (requiresUnmetered) {
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED);
} else if (requiresAnyConnectivity) {
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
}
builder.setRequiresDeviceIdle(mRequiresIdleCheckbox.isChecked());
builder.setRequiresCharging(mRequiresChargingCheckBox.isChecked());
// Extras, work duration.
PersistableBundle extras = new PersistableBundle();
String workDuration = mDurationTimeEditText.getText().toString();
if (TextUtils.isEmpty(workDuration)) {
workDuration = "1";
}
extras.putLong(WORK_DURATION_KEY, Long.valueOf(workDuration) * 1000);
builder.setExtras(extras);
// Schedule job
Log.d(TAG, "Scheduling job");
JobScheduler tm = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
tm.schedule(builder.build());
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void bindJobScheduler() {
// JobScheduler for auto clean sqlite
JobInfo job = new JobInfo.Builder(JOB_ID, new ComponentName(this, SyncJobService.class))
.setRequiresCharging(true)
.setRequiresDeviceIdle(true)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
.setPeriodic(24*60*60*1000)
.setPersisted(true)
.build();
JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
jobScheduler.cancel(JOB_ID);
jobScheduler.schedule(job);
}