类android.app.job.JobScheduler源码实例Demo

下面列出了怎么用android.app.job.JobScheduler的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: Tok-Android   文件: KeepAliveJobService.java
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);
    }

}
 
源代码3 项目: android_9.0.0_r45   文件: TimeZoneUpdateIdler.java
/**
 * 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());
}
 
源代码4 项目: qiscus-sdk-android   文件: QiscusSyncJobService.java
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;
}
 
源代码6 项目: android-sdk   文件: ServiceScheduler.java
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();
    }
}
 
源代码7 项目: shortyz   文件: BackgroundDownloadService.java
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");
    }
}
 
源代码8 项目: InviZible   文件: TorFragmentPresenter.java
@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());
        }
    }
}
 
源代码9 项目: InviZible   文件: TorFragmentPresenter.java
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);
        }
    }
 
源代码10 项目: Zom-Android-XMPP   文件: RemoteImService.java
@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);
}
 
源代码11 项目: your-local-weather   文件: YourLocalWeather.java
@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());
    }
}
 
源代码12 项目: your-local-weather   文件: UpdateWeatherService.java
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);
    }
}
 
源代码14 项目: android-beacon-library   文件: BluetoothMedic.java
@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());
    }
}
 
源代码15 项目: android-job   文件: JobRescheduleTest.java
@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);
}
 
源代码16 项目: Wrox-ProfessionalAndroid-4E   文件: MyActivity.java
@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());
}
 
源代码19 项目: androidtv-sample-inputs   文件: RichBootReceiver.java
@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);
            }
        }
    }
}
 
源代码20 项目: ti.goosh   文件: GcmJobService.java
@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);
	}
}
 
源代码21 项目: ml-authentication   文件: BootReceiver.java
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);
}
 
源代码22 项目: mimi-reader   文件: RefreshScheduler.java
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);
}
 
源代码23 项目: mollyim-android   文件: JobSchedulerScheduler.java
@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());
}
 
源代码24 项目: android-sdk   文件: ServiceScheduler.java
@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);
}
 
源代码26 项目: android_9.0.0_r45   文件: CameraStatsJobService.java
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());

    }
 
源代码27 项目: codeexamples-android   文件: Util.java
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());
}
 
源代码28 项目: 365browser   文件: NotificationService.java
@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);
    }
}
 
源代码29 项目: android-JobScheduler   文件: MainActivity.java
/**
 * 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());
}
 
源代码30 项目: Clip-Stack   文件: CBWatcherService.java
@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);
}
 
 类所在包
 同包方法