android.app.job.JobScheduler Java Examples

The following examples show how to use android.app.job.JobScheduler. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: YourLocalWeather.java    From your-local-weather with GNU General Public License v3.0 8 votes vote down vote up
@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());
    }
}
 
Example #2
Source File: KeepAliveJobService.java    From Tok-Android with GNU General Public License v3.0 7 votes vote down vote up
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);
}
 
Example #3
Source File: TorFragmentPresenter.java    From InviZible with GNU General Public License v3.0 7 votes vote down vote up
@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());
        }
    }
}
 
Example #4
Source File: QiscusNetworkCheckerJobService.java    From qiscus-sdk-android with Apache License 2.0 6 votes vote down vote up
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);
    }

}
 
Example #5
Source File: MobileMessagingJobService.java    From mobile-messaging-sdk-android with Apache License 2.0 6 votes vote down vote up
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");
    }
}
 
Example #6
Source File: RichBootReceiver.java    From androidtv-sample-inputs with Apache License 2.0 6 votes vote down vote up
@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);
            }
        }
    }
}
 
Example #7
Source File: AddWatchNextService.java    From leanback-homescreen-channels with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example #8
Source File: TimeZoneUpdateIdler.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * 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());
}
 
Example #9
Source File: BluetoothMedic.java    From android-beacon-library with Apache License 2.0 6 votes vote down vote up
@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());
    }
}
 
Example #10
Source File: GcmJobService.java    From ti.goosh with MIT License 6 votes vote down vote up
@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);
	}
}
 
Example #11
Source File: QiscusSyncJobService.java    From qiscus-sdk-android with Apache License 2.0 6 votes vote down vote up
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);
    }

}
 
Example #12
Source File: MyActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #13
Source File: JobRescheduleTest.java    From android-job with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #14
Source File: MainActivity.java    From Android-Developer-Fundamentals-Version-2 with GNU General Public License v3.0 6 votes vote down vote up
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);
    }
}
 
Example #15
Source File: ServiceScheduler.java    From android-sdk with Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example #16
Source File: UpdateWeatherService.java    From your-local-weather with GNU General Public License v3.0 6 votes vote down vote up
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);
    }
}
 
Example #17
Source File: BackgroundDownloadService.java    From shortyz with GNU General Public License v3.0 6 votes vote down vote up
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");
    }
}
 
Example #18
Source File: TorFragmentPresenter.java    From InviZible with GNU General Public License v3.0 6 votes vote down vote up
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);
        }
    }
 
Example #19
Source File: BackgroundTaskSchedulerJobService.java    From 365browser with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #20
Source File: RemoteImService.java    From Zom-Android-XMPP with GNU General Public License v3.0 6 votes vote down vote up
@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);
}
 
Example #21
Source File: AbstractAppJob.java    From your-local-weather with GNU General Public License v3.0 5 votes vote down vote up
protected void reScheduleNextAlarm(int jobId, long updatePeriod, Class serviceClass) {
    appendLog(getBaseContext(), TAG, "next alarm:", updatePeriod,
            ", serviceClass=", serviceClass);
    ComponentName serviceComponent = new ComponentName(this, serviceClass);
    JobInfo.Builder builder = new JobInfo.Builder(jobId, serviceComponent);
    builder.setMinimumLatency(updatePeriod); // wait at least
    builder.setOverrideDeadline(updatePeriod + (3 * 1000)); // maximum delay
    JobScheduler jobScheduler = getSystemService(JobScheduler.class);
    jobScheduler.schedule(builder.build());
}
 
Example #22
Source File: WidgetProviderTest.java    From materialistic with Apache License 2.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Before
public void setUp() {
    widgetProvider = new WidgetProvider();
    alarmManager = (AlarmManager) RuntimeEnvironment.application.getSystemService(Context.ALARM_SERVICE);
    jobScheduler = (JobScheduler) RuntimeEnvironment.application.getSystemService(Context.JOB_SCHEDULER_SERVICE);
    widgetManager = AppWidgetManager.getInstance(RuntimeEnvironment.application);
    appWidgetId = shadowOf(widgetManager).createWidget(WidgetProvider.class, R.layout.appwidget);
}
 
Example #23
Source File: MainActivity.java    From your-local-weather with GNU General Public License v3.0 5 votes vote down vote up
private void startAlarms() {
    appendLog(this, TAG, "scheduleStart at boot, SDK=", Build.VERSION.SDK_INT);
    if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M) {
        JobScheduler jobScheduler = getSystemService(JobScheduler.class);
        boolean scheduled = false;
        for (JobInfo jobInfo: jobScheduler.getAllPendingJobs()) {
            if (jobInfo.getId() > 0) {
                appendLog(this, TAG, "scheduleStart does not start - it's scheduled already");
                scheduled = true;
                break;
            }
        }
        if (!scheduled) {
            appendLog(this, TAG, "scheduleStart at MainActivity");
            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());
        }
    } else {
        Intent intentToStartUpdate = new Intent("org.thosp.yourlocalweather.action.START_ALARM_SERVICE");
        intentToStartUpdate.setPackage("org.thosp.yourlocalweather");
        startService(intentToStartUpdate);
    }
}
 
Example #24
Source File: AppUtils.java    From ClassSchedule with Apache License 2.0 5 votes vote down vote up
/**
 * 取消widget更新任务
 */
public static void cancelUpdateWidgetService(Context context) {
    LogUtil.e(AppUtils.class, "cancelUpdateWidgetService");
    JobScheduler scheduler = (JobScheduler) context
            .getSystemService(Context.JOB_SCHEDULER_SERVICE);
    scheduler.cancel(UPDATE_WIDGET_JOB_ID);
}
 
Example #25
Source File: JobIntentService.java    From Telegram with GNU General Public License v2.0 5 votes vote down vote up
JobWorkEnqueuer(Context context, ComponentName cn, int jobId) {
    super(context, cn);
    ensureJobId(jobId);
    JobInfo.Builder b = new JobInfo.Builder(jobId, mComponentName);
    mJobInfo = b.setOverrideDeadline(0).setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY).build();
    mJobScheduler = (JobScheduler) context.getApplicationContext().getSystemService(
            Context.JOB_SCHEDULER_SERVICE);
}
 
Example #26
Source File: StartupReceiver.java    From your-local-weather with GNU General Public License v3.0 5 votes vote down vote up
private void scheduleStart(Context context) {
    appendLog(context, TAG, "scheduleStart at boot, SDK=", Build.VERSION.SDK_INT);
    if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M) {
        ComponentName serviceComponent = new ComponentName(context, 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 jobScheduler = context.getSystemService(JobScheduler.class);
        jobScheduler.schedule(builder.build());
    } else {
        Intent intentToStartUpdate = new Intent("org.thosp.yourlocalweather.action.START_ALARM_SERVICE");
        intentToStartUpdate.setPackage("org.thosp.yourlocalweather");
        context.startService(intentToStartUpdate);
    }
}
 
Example #27
Source File: NextAlarmUpdaterJob.java    From hassalarm with MIT License 5 votes vote down vote up
/**
 * Schedule a job to update the next alarm once we have some kind of network connection.
 */
public static void scheduleJob(Context context) {
    Log.d(Constants.LOG_TAG, "Scheduling job");
    final JobInfo jobInfo = new JobInfo.Builder(JOB_ID,
            new ComponentName(context, NextAlarmUpdaterJob.class))
            .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
            .setRequiresCharging(false)
            .setRequiresDeviceIdle(false)
            .setOverrideDeadline(MAX_EXECUTION_DELAY_MS)
            .build();
    JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
    jobScheduler.schedule(jobInfo);
}
 
Example #28
Source File: DeleteWatchNextService.java    From leanback-homescreen-channels with Apache License 2.0 5 votes vote down vote up
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))
            .setExtras(bundle)
            .build());
}
 
Example #29
Source File: PlatformScheduler.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
@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;
}
 
Example #30
Source File: AppUtils.java    From ClassSchedule with Apache License 2.0 5 votes vote down vote up
private static boolean isJobPollServiceOn(Context context) {
    JobScheduler scheduler = (JobScheduler) context
            .getSystemService(Context.JOB_SCHEDULER_SERVICE);

    for (JobInfo jobInfo : scheduler.getAllPendingJobs()) {
        if (jobInfo.getId() == UPDATE_WIDGET_JOB_ID) {
            return true;
        }
    }
    return false;
}