@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Create JobScheduler JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE); //Create a component passing the JobService that we want to use ComponentName jobService = new ComponentName(getPackageName(), MyJobService.class.getName()); //Create a JobInfo passing a unique JOB_ID and the jobService //also set the periodic time to repeat this job JobInfo jobInfo = new JobInfo.Builder(JOB_ID, jobService) .setPeriodic(REFRESH_INTERVAL) .build(); jobScheduler.schedule(jobInfo); }
@Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { final String remindersKey = getString(R.string.pref_key_reminders); if (key.equals(remindersKey)) { boolean enabled = sharedPreferences.getBoolean(remindersKey, false); JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE); if (!enabled) { jobScheduler.cancel(JOB_ID); Log.d(TAG, "cancelling scheduled job"); } else { long interval = AlarmManager.INTERVAL_HOUR; JobInfo job = new JobInfo.Builder(JOB_ID, new ComponentName(getPackageName(), ScheduledJobService.class.getName())) .setPersisted(true) .setPeriodic(interval) .build(); jobScheduler.schedule(job); Log.d(TAG, "setting scheduled job for: " + interval); } } }
/** * Set XMPush sdk enable * @param enable enable * @param context context param */ public static void setServiceEnable (boolean enable, Context context) { if (enable && isAppMainProc(context)) { MiPushClient.registerPush(wrapContext(context), APP_ID, APP_KEY); } else { MiPushClient.unregisterPush(wrapContext(context)); // Force stop and disable services. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { JobScheduler scheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); scheduler.cancelAll(); } context.stopService(new Intent(context, XMPushService.class)); } }
@Test(timeout = 5000) public void testProcessOnePacket() throws Exception { DataPacket dataPacket = new ByteArrayDataPacket(Collections.singletonMap("id", "testId"), "testPayload".getBytes(Charsets.UTF_8)); queuedSiteToSiteClientConfig.createQueuedClient(context).enqueue(dataPacket); mockNiFiS2SServer.enqueueSiteToSitePeers(Collections.singletonList(peer)); String transactionPath = mockNiFiS2SServer.enqueuCreateTransaction(portIdentifier, transactionIdentifier, 30); mockNiFiS2SServer.enqueuDataPackets(transactionPath, Collections.singletonList(dataPacket), queuedSiteToSiteClientConfig); mockNiFiS2SServer.enqueueTransactionComplete(transactionPath, 2, ResponseCode.CONFIRM_TRANSACTION, ResponseCode.CONFIRM_TRANSACTION); JobInfo.Builder processJobInfoBuilder = SiteToSiteJobService.createProcessJobInfoBuilder(context, 1, queuedSiteToSiteClientConfig, parcelableQueuedOperationResultCallback); processJobInfoBuilder.setOverrideDeadline(0); JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); assertEquals(JobScheduler.RESULT_SUCCESS, jobScheduler.schedule(processJobInfoBuilder.build())); assertEquals(1, parcelableQueuedOperationResultCallback.getInvocations().size()); SiteToSiteDBTestUtil.assertNoQueuedPackets(siteToSiteDB); mockNiFiS2SServer.verifyAssertions(); }
@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(SyncJobService.PREFERENCE_EPG_SYNC, Context.MODE_PRIVATE).getString(SyncJobService.BUNDLE_KEY_INPUT_ID, null); if (inputId != null) { // Set up periodic sync only when input has set up. SyncUtils.setUpPeriodicSync(context, inputId); } 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); } } } }
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)) .setMinimumLatency(0) .setExtras(bundle) .build()); }
@Test public void testStart() { Context context = InstrumentationRegistry.getTargetContext(); QuickPeriodicJobScheduler qpjs = new QuickPeriodicJobScheduler(context); qpjs.start(2, 30000l); SystemClock.sleep(1000); JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); List<JobInfo> jobInfoList = jobScheduler.getAllPendingJobs(); JobInfo jobInfo = null; for(JobInfo job : jobInfoList) { if(job.getId() == 2) { jobInfo = job; } } Assert.assertEquals(jobInfo.getMaxExecutionDelayMillis(), 30000l); Assert.assertEquals(jobInfo.getMinLatencyMillis(), 30000l); Assert.assertEquals(jobInfo.getId(), 2); Assert.assertEquals(jobInfo.getExtras().getLong("interval"), 30000l); Assert.assertNotNull(jobInfo); }
@SuppressWarnings("ConstantConditions") public static void schedule(final Context context) { final JobScheduler scheduler = context.getSystemService(JobScheduler.class); for (final JobInfo job : scheduler.getAllPendingJobs()) { if (job.getId() == JOB_ID_PERIODIC) { return; } } final long interval = MINUTE * Integer.valueOf(DefaultSharedPrefUtils.getBackgroundServiceInterval(context)); final ComponentName name = new ComponentName(context, PeriodicJob.class); final int result = scheduler.schedule(new JobInfo.Builder(JOB_ID_PERIODIC, name) .setPeriodic(interval) .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY) .build()); if (result != JobScheduler.RESULT_SUCCESS) { Log.e(TAG, "Failed to schedule periodic job"); } }
public static void schedule(Context context) { SharedPreferences settings = AppSettings.getSharedPreferences(context); int notificationsFrequency = AppSettings.Notifications.getNotificationsFrequency(settings); ComponentName component = new ComponentName(context, NotificationsJobService.class); JobInfo.Builder builder = new JobInfo.Builder(JOB_ID, component) .setPeriodic(60000 * notificationsFrequency); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_NOT_ROAMING); else builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY); JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); jobScheduler.schedule(builder.build()); }
@TargetApi(21) public static void startPolling(Context context) { JobScheduler scheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); final int JOB_ID = 1; if (isBeenScheduled(JOB_ID, context)){ Log.i(TAG, "scheduler.cancel(JOB_ID)"); scheduler.cancel(JOB_ID); } else{ Log.i(TAG, "scheduler.schedule(jobInfo)"); int pollInterval = QueryPreferences.getPollInterval(context); Log.i(TAG, "the poll interval is: " + pollInterval + " ms"); JobInfo jobInfo = new JobInfo.Builder( JOB_ID, new ComponentName(context, PollJobService.class)) .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED) .setPeriodic(pollInterval) .setPersisted(true) .build(); scheduler.schedule(jobInfo); } }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.job_list_activity); RecyclerView rv = (RecyclerView)findViewById(R.id.jobList); // Set the recycler view layout LinearLayoutManager llm = new LinearLayoutManager(this); rv.setLayoutManager(llm); initList(); Button cancelAllBut = (Button)findViewById(R.id.cancelAllBut); cancelAllBut.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { JobScheduler jobScheduler = (JobScheduler)getSystemService(JOB_SCHEDULER_SERVICE); jobScheduler.cancelAll(); initList(); Toast.makeText(JobListActivity.this, "Cancelling all the pending jobs", Toast.LENGTH_LONG).show(); } }); }
@Override public void onBindViewHolder(JobListRecyclerAdapter.JobViewHolder holder, int position) { final JobInfo ji= mJobList.get(position); holder.jobId.setText(Integer.toString(ji.getId())); holder.serviceName.setText(ji.getService().getClassName()); holder.stopBut.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { JobScheduler jobScheduler = (JobScheduler)mContext.getSystemService(mContext.JOB_SCHEDULER_SERVICE); jobScheduler.cancel(ji.getId()); Log.i("JobList", "Stopping the job "+ji.getId()); Toast.makeText(mContext, "Canceling the job "+ji.getId(), Toast.LENGTH_LONG).show(); mContext.initList(); } }); }
private static void schedulePeriodic(Context context) { Timber.d("Scheduling a periodic task"); JobInfo.Builder builder = new JobInfo.Builder( PERIODIC_ID, new ComponentName(context, QuoteJobService.class)); builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY) .setPeriodic(PERIOD) .setBackoffCriteria(INITIAL_BACKOFF, JobInfo.BACKOFF_POLICY_EXPONENTIAL); JobScheduler scheduler = (JobScheduler) context.getSystemService( Context.JOB_SCHEDULER_SERVICE); int result = scheduler.schedule(builder.build()); if (result == JobScheduler.RESULT_SUCCESS) { Timber.i("Job scheduled successfully!"); } else { Timber.e("Job did not scheduled!"); } }
private void syncJob() { QiscusAccount qiscusAccount = Qiscus.getQiscusAccount(); Random rand = new Random(); int randomValue = rand.nextInt(50); JobInfo jobInfo = new JobInfo.Builder(qiscusAccount.getId() + randomValue, componentName) .setPeriodic(TimeUnit.MINUTES.toMillis(15)) .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY) .build(); JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE); if (jobScheduler != null) { jobScheduler.schedule(jobInfo); } }
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"); } }
@Override public void onReceive(Context context, Intent intent) { Log.d(getClass().getName(), "onReceive"); // // Automatically open application // Intent bootIntent = new Intent(context, MainActivity.class); // bootIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // context.startActivity(bootIntent); // Initiate background job for synchronizing with server content ComponentName componentName = new ComponentName(context, ContentSynchronizationJobService.class); JobInfo.Builder builder = new JobInfo.Builder(LiteracyApplication.CONTENT_SYNCRHONIZATION_JOB_ID, componentName); builder.setPeriodic(1000 * 60 * 30); // Every 30 minutes JobInfo jobInfo = builder.build(); JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); jobScheduler.schedule(jobInfo); /*if (StartPrefsHelper.scheduleAfterBoot(context)){ scheduleAuthenticationJobs(context); } else { Log.i(getClass().getName(), "Authentication jobs won't be scheduled because the 7 days after first start-up haven't passed yet."); }*/ scheduleAuthenticationJobs(context); }
@Test public void testScheduledJob() { PreferenceManager.getDefaultSharedPreferences(RuntimeEnvironment.application) .edit() .putBoolean(RuntimeEnvironment.application.getString(R.string.pref_saved_item_sync), true) .apply(); shadowOf((ConnectivityManager) RuntimeEnvironment.application .getSystemService(Context.CONNECTIVITY_SERVICE)) .setActiveNetworkInfo(ShadowNetworkInfo.newInstance(null, ConnectivityManager.TYPE_WIFI, 0, true, true)); new SyncScheduler().scheduleSync(RuntimeEnvironment.application, "1"); List<JobInfo> pendingJobs = shadowOf((JobScheduler) RuntimeEnvironment.application .getSystemService(Context.JOB_SCHEDULER_SERVICE)).getAllPendingJobs(); assertThat(pendingJobs).isNotEmpty(); JobInfo actual = pendingJobs.get(0); assertThat(actual.getService().getClassName()) .isEqualTo(ItemSyncJobService.class.getName()); }
private void waitForNetwork() { // SDK check! We'll go with JobScheduler if we can. if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // JobScheduler time! It's fancier! JobScheduler js = (JobScheduler)getSystemService(Context.JOB_SCHEDULER_SERVICE); JobInfo job = new JobInfo.Builder( ALARM_CONNECTIVITY_JOB, new ComponentName(this, AlarmServiceJobService.class)) .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY) .build(); js.schedule(job); } else { // Otherwise, just use the ol' package component. AndroidUtil.setPackageComponentEnabled(this, NetworkReceiver.class, true); } }
private void showWaitingForConnectionNotification() { Notification.Builder builder = getFreshNotificationBuilder() .setOngoing(true) .setContentTitle(getString(R.string.wiki_notification_waiting_for_connection_title)) .setContentText(getString(R.string.wiki_notification_waiting_for_connection_content)) .setSmallIcon(R.drawable.ic_stat_navigation_more_horiz) .setContentIntent(getBasicCommandIntent(QueueService.COMMAND_RESUME)); mNotificationManager.notify(R.id.wiki_waiting_notification, builder.build()); // If we have JobScheduler (SDK 21 or higher), use that. Otherwise, go // with the old ConnectivityListener style. if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { JobScheduler js = (JobScheduler)getSystemService(Context.JOB_SCHEDULER_SERVICE); JobInfo job = new JobInfo.Builder( WIKI_CONNECTIVITY_JOB, new ComponentName(this, WikiServiceJobService.class)) .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY) .build(); js.schedule(job); } else { // Make sure the connectivity listener's waiting for a connection. AndroidUtil.setPackageComponentEnabled(this, WikiServiceConnectivityListener.class, true); } }
@Override protected void onResume() { super.onResume(); // Change locale to Klingon if Klingon UI option is set. updateLocaleConfiguration(); // Schedule the KWOTD service if it hasn't already been started. It's necessary to do this here // because the setting might have changed in Preferences. SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); if (sharedPrefs.getBoolean(Preferences.KEY_KWOTD_CHECKBOX_PREFERENCE, /* default */ true)) { runKwotdServiceJob(/* isOneOffJob */ false); } else { // If the preference is unchecked, cancel the persisted job. JobScheduler scheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE); scheduler.cancel(KWOTD_SERVICE_PERSISTED_JOB_ID); } }
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"); } }
@Test @Config(sdk = Build.VERSION_CODES.LOLLIPOP_MR1) 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); }
@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; }
public static void setupIfNeededPeriodicWallpaperChange(Context context) { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { Resources res = context.getResources(); JobScheduler scheduler = (JobScheduler) context .getSystemService(Context.JOB_SCHEDULER_SERVICE); if (scheduler.getAllPendingJobs().size() == 0) { ComponentName serviceEndpoint = new ComponentName(context, PeriodicWallpaperChangeService.class); JobInfo wallpaperChangeJob = new JobInfo.Builder( PeriodicWallpaperChangeService.JOB_ID, serviceEndpoint) .setRequiresCharging(false) .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY) .setPersisted(true) .setRequiresDeviceIdle(true) .setPeriodic(PERIOD_IN_HOURS * 60 * 60 * 1000) .build(); scheduler.schedule(wallpaperChangeJob); String scheduledMessage = res.getString(R.string.periodic_change_scheduled); Toast.makeText(context, scheduledMessage, Toast.LENGTH_SHORT).show(); } } }
@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); } } } }
private void scheduleRetryArtworkDownload() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE); jobScheduler.schedule(new JobInfo.Builder(LOAD_ARTWORK_JOB_ID, new ComponentName(this, DownloadArtworkJobService.class)) .setRequiredNetworkType(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ? JobInfo.NETWORK_TYPE_NOT_ROAMING : JobInfo.NETWORK_TYPE_ANY) .build()); } else { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); int reloadAttempt = sp.getInt(PREF_ARTWORK_DOWNLOAD_ATTEMPT, 0); sp.edit().putInt(PREF_ARTWORK_DOWNLOAD_ATTEMPT, reloadAttempt + 1).apply(); AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); long retryTimeMillis = SystemClock.elapsedRealtime() + (1 << reloadAttempt) * 2000; am.set(AlarmManager.ELAPSED_REALTIME, retryTimeMillis, TaskQueueService.getArtworkDownloadRetryPendingIntent(this)); } }
public static Intent maybeRetryDownloadDueToGainedConnectivity(Context context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); List<JobInfo> pendingJobs = jobScheduler.getAllPendingJobs(); for (JobInfo pendingJob : pendingJobs) { if (pendingJob.getId() == LOAD_ARTWORK_JOB_ID) { return TaskQueueService.getDownloadCurrentArtworkIntent(context); } } return null; } return (PreferenceManager.getDefaultSharedPreferences(context) .getInt(PREF_ARTWORK_DOWNLOAD_ATTEMPT, 0) > 0) ? TaskQueueService.getDownloadCurrentArtworkIntent(context) : null; }
static void scheduleComplicationUpdateJob(Context context) { JobScheduler jobScheduler = context.getSystemService(JobScheduler.class); ComponentName componentName = new ComponentName(context, ArtworkComplicationJobService.class); int result = jobScheduler.schedule(new JobInfo.Builder(ARTWORK_COMPLICATION_JOB_ID, componentName) .addTriggerContentUri(new JobInfo.TriggerContentUri( MuzeiContract.Artwork.CONTENT_URI, JobInfo.TriggerContentUri.FLAG_NOTIFY_FOR_DESCENDANTS)) .build()); if (BuildConfig.DEBUG) { Log.d(TAG, "Job scheduled with " + (result == JobScheduler.RESULT_SUCCESS ? "success" : "failure")); } // Enable the BOOT_COMPLETED receiver to reschedule the job on reboot ComponentName bootReceivedComponentName = new ComponentName(context, ArtworkComplicationBootReceiver.class); context.getPackageManager().setComponentEnabledSetting(bootReceivedComponentName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); }
/** * UI onclick listener to schedule a new job. */ public void scheduleJob(View v) { JobInfo.Builder builder = new JobInfo.Builder(kJobId++,mServiceComponent); String delay = mDelayEditText.getText().toString(); if (delay != null && !TextUtils.isEmpty(delay)) { builder.setMinimumLatency(Long.valueOf(delay) * 1000); } String deadline = mDeadlineEditText.getText().toString(); if (deadline != null && !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()); JobScheduler jobScheduler = (JobScheduler) getApplication().getSystemService(Context.JOB_SCHEDULER_SERVICE); jobScheduler.schedule(builder.build()); }
/** * 用于在不需要服务运行的时候取消 Job / Alarm / Subscription. * * 因 WatchDogService 运行在 :watch 子进程, 请勿在主进程中直接调用此方法. * 而是向 WakeUpReceiver 发送一个 Action 为 WakeUpReceiver.ACTION_CANCEL_JOB_ALARM_SUB 的广播. */ public static void cancelJobAlarmSub() { if (!DaemonEnv.sInitialized) return; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { JobScheduler scheduler = (JobScheduler) DaemonEnv.sApp.getSystemService(JOB_SCHEDULER_SERVICE); scheduler.cancel(HASH_CODE); } else { AlarmManager am = (AlarmManager) DaemonEnv.sApp.getSystemService(ALARM_SERVICE); if (sPendingIntent != null) am.cancel(sPendingIntent); } if (sDisposable != null) sDisposable.dispose(); }
@Before public void setup() { context = RuntimeEnvironment.application; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { scheduler = new JobSchedulerSchedulerV26(context); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { scheduler = new JobSchedulerSchedulerV24(context); } else { scheduler = new JobSchedulerSchedulerV21(context); } jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); }
/** Starts the {@link ColorExtractionService} without checking the wallpaper id */ static void startColorExtractionService(Context context) { JobScheduler jobScheduler = (JobScheduler) context.getSystemService( Context.JOB_SCHEDULER_SERVICE); jobScheduler.schedule(new JobInfo.Builder(Utilities.COLOR_EXTRACTION_JOB_ID, new ComponentName(context, ColorExtractionService.class)) .setMinimumLatency(0).build()); }
@Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(TAG, "onStartCommand(): intent = [" + intent.toUri(0) + "], flags = [" + flags + "], startId = [" + startId + "]"); try { // 定时检查 WorkService 是否在运行,如果不在运行就把它拉起来 // Android 5.0+ 使用 JobScheduler,效果比 AlarmManager 好 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Log.i(TAG, "开启 JobService 定时"); JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE); jobScheduler.cancelAll(); JobInfo.Builder builder = new JobInfo.Builder(1024, new ComponentName(getPackageName(), ScheduleService.class.getName())); builder.setPeriodic(WAKE_INTERVAL); builder.setPersisted(true); builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY); int schedule = jobScheduler.schedule(builder.build()); if (schedule <= 0) { Log.w(TAG, "schedule error!"); } } else { // Android 4.4- 使用 AlarmManager Log.i(TAG, "开启 AlarmManager 定时"); AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); Intent alarmIntent = new Intent(getApplication(), DaemonService.class); PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 1024, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT); am.cancel(pendingIntent); am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + WAKE_INTERVAL, WAKE_INTERVAL, pendingIntent); } } catch (Exception e) { Log.e(TAG, "e:", e); } // 简单守护开机广播 getPackageManager().setComponentEnabledSetting( new ComponentName(getPackageName(), DaemonService.class.getName()), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); return super.onStartCommand(intent, flags, startId); }
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public void jobSchedule(View view) { JobInfo.Builder processJobInfoBuilder = SiteToSiteJobService.createProcessJobInfoBuilder(getApplicationContext(), 1234, siteToSiteClientConfig, new JobSchedulerCallback()); processJobInfoBuilder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED); processJobInfoBuilder.setRequiresCharging(true); JobScheduler jobScheduler = (JobScheduler) getApplicationContext().getSystemService(Context.JOB_SCHEDULER_SERVICE); jobScheduler.schedule(processJobInfoBuilder.build()); }
@Test(timeout = 5000) public void testProcessNoPackets() throws PendingIntent.CanceledException, InterruptedException { JobInfo.Builder processJobInfoBuilder = SiteToSiteJobService.createProcessJobInfoBuilder(context, 1, queuedSiteToSiteClientConfig, parcelableQueuedOperationResultCallback); processJobInfoBuilder.setOverrideDeadline(0); JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); assertEquals(JobScheduler.RESULT_SUCCESS, jobScheduler.schedule(processJobInfoBuilder.build())); assertEquals(1, parcelableQueuedOperationResultCallback.getInvocations().size()); SiteToSiteDBTestUtil.assertNoQueuedPackets(siteToSiteDB); }
@Test(timeout = 25000) public void testProcessAThousandPackets() throws Exception { int numPackets = 1000; List<DataPacket> dataPackets = new ArrayList<>(numPackets); for (int i = 0; i < numPackets; i++) { dataPackets.add(new ByteArrayDataPacket(Collections.singletonMap("id", "testId" + i), ("testPayload" + i).getBytes(Charsets.UTF_8))); } queuedSiteToSiteClientConfig.createQueuedClient(context).enqueue(dataPackets.iterator()); SiteToSiteDBTestUtil.assertQueuedPacketCount(siteToSiteDB, numPackets); Collections.reverse(dataPackets); mockNiFiS2SServer.enqueueSiteToSitePeers(Collections.singletonList(peer)); for (int i = 0; i < numPackets; i+= 100) { String transactionPath = mockNiFiS2SServer.enqueuCreateTransaction(portIdentifier, transactionIdentifier, 30); mockNiFiS2SServer.enqueuDataPackets(transactionPath, dataPackets.subList(i, i + 100), queuedSiteToSiteClientConfig); mockNiFiS2SServer.enqueueTransactionComplete(transactionPath, 2, ResponseCode.CONFIRM_TRANSACTION, ResponseCode.CONFIRM_TRANSACTION); } JobInfo.Builder processJobInfoBuilder = SiteToSiteJobService.createProcessJobInfoBuilder(context, 3, queuedSiteToSiteClientConfig, parcelableQueuedOperationResultCallback); processJobInfoBuilder.setOverrideDeadline(0); JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); assertEquals(JobScheduler.RESULT_SUCCESS, jobScheduler.schedule(processJobInfoBuilder.build())); assertEquals(1, parcelableQueuedOperationResultCallback.getInvocations().size()); SiteToSiteDBTestUtil.assertNoQueuedPackets(siteToSiteDB); mockNiFiS2SServer.verifyAssertions(); }
@Override public void onCreate() { super.onCreate(); dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { jobScheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE); } Realm.init(this); RealmConfiguration config = new RealmConfiguration.Builder().build(); Realm.setDefaultConfiguration(config); }
public void startJobSheduler() { try { JobInfo.Builder builder = new JobInfo.Builder(1, new ComponentName(getPackageName(), MyService.class.getName())); builder.setPeriodic(5); builder.setPersisted(true); JobScheduler jobScheduler = (JobScheduler) this.getSystemService(Context.JOB_SCHEDULER_SERVICE); jobScheduler.schedule(builder.build()); } catch (Exception ex) { ex.printStackTrace(); } }
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override public void schedule(long elapsedRealTime) { JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); jobScheduler.schedule(new JobInfo.Builder(SCHEDULER_FLUSHER_JOB_ID, new ComponentName(context, SchedulerFlusherJobService.class)) .setPeriodic(FLUSHING_PERIOD_IN_MILLIS) .build()); }
public static void scheduleDeleteWatchNextRequest(Context context, String clipId) { JobScheduler scheduler = (JobScheduler) context.getSystemService(JOB_SCHEDULER_SERVICE); PersistableBundle bundle = new PersistableBundle(); bundle.putString(ID_KEY, clipId); scheduler.schedule(new JobInfo.Builder(1, new ComponentName(context, DeleteWatchNextService.class)) .setMinimumLatency(0) .setExtras(bundle) .build()); }