Example usage for android.app.job JobScheduler schedule

List of usage examples for android.app.job JobScheduler schedule

Introduction

In this page you can find the example usage for android.app.job JobScheduler schedule.

Prototype

public abstract @Result int schedule(@NonNull JobInfo job);

Source Link

Document

Schedule a job to be executed.

Usage

From source file:com.commonsware.android.jobsched.content.DemoJobService.java

static void schedule(Context ctxt) {
    ComponentName cn = new ComponentName(ctxt, DemoJobService.class);
    JobInfo.TriggerContentUri trigger = new JobInfo.TriggerContentUri(CONTENT_URI,
            JobInfo.TriggerContentUri.FLAG_NOTIFY_FOR_DESCENDANTS);
    JobInfo.Builder b = new JobInfo.Builder(ME_MYSELF_AND_I, cn).addTriggerContentUri(trigger);
    JobScheduler jobScheduler = (JobScheduler) ctxt.getSystemService(Context.JOB_SCHEDULER_SERVICE);

    jobScheduler.schedule(b.build());
}

From source file:com.example.android.sampletvinput.syncservice.SyncUtils.java

/** Send the job to JobScheduler. **/
private static void scheduleJob(Context context, JobInfo job) {
    JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
    jobScheduler.schedule(job);
}

From source file:com.google.android.media.tv.companionlibrary.EpgSyncJobService.java

/** Send the job to JobScheduler. */
private static void scheduleJob(Context context, JobInfo job) {
    JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
    int result = jobScheduler.schedule(job);
    Assert.assertEquals(result, JobScheduler.RESULT_SUCCESS);
    if (DEBUG) {//w  ww . j  a  va  2s .c  o m
        Log.d(TAG, "Scheduling result is " + result);
    }
}

From source file:com.google.android.apps.muzei.sync.TaskQueueService.java

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(JobInfo.NETWORK_TYPE_ANY).build());
    } else {//from   ww w . ja va  2s  . c o  m
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        int reloadAttempt = sp.getInt(PREF_ARTWORK_DOWNLOAD_ATTEMPT, 0);
        sp.edit().putInt(PREF_ARTWORK_DOWNLOAD_ATTEMPT, reloadAttempt + 1).commit();
        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        long retryTimeMillis = SystemClock.elapsedRealtime() + (1 << reloadAttempt) * 2000;
        am.set(AlarmManager.ELAPSED_REALTIME, retryTimeMillis,
                TaskQueueService.getArtworkDownloadRetryPendingIntent(this));
    }
}

From source file:com.commonsware.android.rv.transcript.EventDemoActivity.java

@Override
@SuppressLint("MissingPermission")
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) {
        getSupportFragmentManager().beginTransaction().add(android.R.id.content, new EventLogFragment())
                .commit();/*w ww. ja va  2 s  .  c  om*/

        JobScheduler jobs = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
        ComponentName cn = new ComponentName(this, ScheduledService.class);
        JobInfo.Builder b = new JobInfo.Builder(JOB_ID, cn).setRequiredNetworkType(JobInfo.NETWORK_TYPE_NONE)
                .setPeriodic(60000).setPersisted(false).setRequiresCharging(false).setRequiresDeviceIdle(false);

        jobs.schedule(b.build());
    }
}

From source file:com.owncloud.android.files.services.TransferRequester.java

/**
 * Schedule a future transfer of an upload, to be done when a connection via an unmetered network (free Wifi)
 * is available./*from ww w . jav  a 2s.  c om*/
 *
 * @param context                   Caller {@link Context}.
 * @param scheduledRetryService     Class of the appropriate retry service, either to retry downloads
 *                                  or to retry uploads.
 * @param jobId                     Identifier to set to the retry job.
 * @param accountName               Local name of the OC account where the upload will be retried.
 * @param remotePath                Full path of the file to upload, relative to root of the OC account.
 */
private boolean scheduleTransfer(Context context, Class<?> scheduledRetryService, int jobId, String accountName,
        String remotePath) {

    // JobShceduler requires Android >= 5.0 ; do not remove this protection while minSdkVersion is lower
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        return false;
    }

    ComponentName serviceComponent = new ComponentName(context, scheduledRetryService);

    JobInfo.Builder builder = new JobInfo.Builder(jobId, serviceComponent);

    int networkType = getRequiredNetworkType(context, accountName, remotePath);

    // require network type (Wifi or Wifi and cellular)
    builder.setRequiredNetworkType(networkType);

    // Persist job and prevent it from being deleted after a device restart
    builder.setPersisted(true);

    // Extra data
    PersistableBundle extras = new PersistableBundle();
    extras.putString(Extras.EXTRA_REMOTE_PATH, remotePath);
    extras.putString(Extras.EXTRA_ACCOUNT_NAME, accountName);
    builder.setExtras(extras);

    JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
    jobScheduler.schedule(builder.build());

    return true;
}

From source file:nuclei.task.TaskScheduler.java

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void onScheduleJobL(Context context) {
    JobInfo.Builder builder = new JobInfo.Builder(mBuilder.mTask.getTaskId(),
            new ComponentName(context, TaskJobService.class));

    ArrayMap<String, Object> map = new ArrayMap<>();
    mBuilder.mTask.serialize(map);/*www . j  a v a  2 s .  c  om*/
    PersistableBundle extras = new PersistableBundle();
    for (Map.Entry<String, Object> entry : map.entrySet()) {
        Object v = entry.getValue();
        if (v == null)
            continue;
        if (v instanceof Integer)
            extras.putInt(entry.getKey(), (int) v);
        else if (v instanceof Double)
            extras.putDouble(entry.getKey(), (double) v);
        else if (v instanceof Long)
            extras.putLong(entry.getKey(), (long) v);
        else if (v instanceof String)
            extras.putString(entry.getKey(), (String) v);
        else if (v instanceof String[])
            extras.putStringArray(entry.getKey(), (String[]) v);
        else if (v instanceof boolean[] && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1)
            extras.putBooleanArray(entry.getKey(), (boolean[]) v);
        else if (v instanceof double[])
            extras.putDoubleArray(entry.getKey(), (double[]) v);
        else if (v instanceof long[])
            extras.putLongArray(entry.getKey(), (long[]) v);
        else if (v instanceof int[])
            extras.putIntArray(entry.getKey(), (int[]) v);
        else
            throw new IllegalArgumentException("Invalid Type: " + entry.getKey());
    }
    extras.putString(TASK_NAME, mBuilder.mTask.getClass().getName());

    switch (mBuilder.mTaskType) {
    case TASK_ONE_OFF:
        if (mBuilder.mWindowStartDelaySecondsSet)
            builder.setMinimumLatency(mBuilder.mWindowStartDelaySeconds * 1000);
        if (mBuilder.mWindowEndDelaySecondsSet)
            builder.setOverrideDeadline(mBuilder.mWindowEndDelaySeconds * 1000);
        break;
    case TASK_PERIODIC:
        builder.setPeriodic(mBuilder.mPeriodInSeconds * 1000);
        break;
    default:
        throw new IllegalArgumentException();
    }

    builder.setExtras(extras).setPersisted(mBuilder.mPersisted).setRequiresCharging(mBuilder.mRequiresCharging)
            .setRequiresDeviceIdle(mBuilder.mRequiresDeviceIdle);

    switch (mBuilder.mNetworkState) {
    case NETWORK_STATE_ANY:
        builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_NONE);
        break;
    case NETWORK_STATE_CONNECTED:
        builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
        break;
    case NETWORK_STATE_UNMETERED:
        builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED);
        break;
    }

    switch (mBuilder.mBackoffPolicy) {
    case BACKOFF_POLICY_EXPONENTIAL:
        builder.setBackoffCriteria(mBuilder.mInitialBackoffMillis, JobInfo.BACKOFF_POLICY_EXPONENTIAL);
        break;
    case BACKOFF_POLICY_LINEAR:
        builder.setBackoffCriteria(mBuilder.mInitialBackoffMillis, JobInfo.BACKOFF_POLICY_LINEAR);
        break;
    }

    JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
    jobScheduler.schedule(builder.build());
}

From source file:eu.faircode.netguard.ServiceJob.java

private static void submit(Rule rule, PersistableBundle bundle, Context context) {
    PackageManager pm = context.getPackageManager();
    JobScheduler scheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);

    // Get english application label
    String label = null;/*from  www .j  a v  a2 s .  co m*/
    try {
        Configuration config = new Configuration();
        config.setLocale(new Locale("en"));
        Resources res = pm.getResourcesForApplication(rule.info.packageName);
        res.updateConfiguration(config, res.getDisplayMetrics());
        label = res.getString(rule.info.applicationInfo.labelRes);
    } catch (Throwable ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        CharSequence cs = rule.info.applicationInfo.loadLabel(pm);
        if (cs != null)
            label = cs.toString();
    }

    // Add application data
    bundle.putInt("uid", rule.info.applicationInfo.uid);
    bundle.putString("package", rule.info.packageName);
    bundle.putInt("version_code", rule.info.versionCode);
    bundle.putString("version_name", rule.info.versionName);
    bundle.putString("label", label);
    bundle.putInt("system", rule.system ? 1 : 0);
    try {
        bundle.putString("installer", pm.getInstallerPackageName(rule.info.packageName));
    } catch (Throwable ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        bundle.putString("installer", null);
    }

    // Cancel overlapping jobs
    for (JobInfo pending : scheduler.getAllPendingJobs()) {
        String type = pending.getExtras().getString("type");
        if (type != null && type.equals(bundle.getString("type"))) {
            if (type.equals("rule")) {
                int uid = pending.getExtras().getInt("uid");
                if (uid == bundle.getInt("uid")) {
                    Log.i(TAG, "Canceling id=" + pending.getId());
                    scheduler.cancel(pending.getId());
                }
            } else if (type.equals("host")) {
                int uid = pending.getExtras().getInt("uid");
                int version = pending.getExtras().getInt("version");
                int protocol = pending.getExtras().getInt("protocol");
                String daddr = pending.getExtras().getString("daddr");
                int dport = pending.getExtras().getInt("dport");
                if (uid == bundle.getInt("uid") && version == bundle.getInt("version")
                        && protocol == bundle.getInt("protocol") && daddr != null
                        && daddr.equals(bundle.getString("daddr")) && dport == bundle.getInt("dport")) {
                    Log.i(TAG, "Canceling id=" + pending.getId());
                    scheduler.cancel(pending.getId());
                }
            }
        }
    }

    // Schedule job
    ComponentName serviceName = new ComponentName(context, ServiceJob.class);
    JobInfo job = new JobInfo.Builder(++id, serviceName).setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
            .setMinimumLatency(Util.isDebuggable(context) ? 10 * 1000 : 60 * 1000).setExtras(bundle)
            .setPersisted(true).build();
    if (scheduler.schedule(job) == JobScheduler.RESULT_SUCCESS)
        Log.i(TAG, "Scheduled job=" + job.getId() + " success");
    else
        Log.e(TAG, "Scheduled job=" + job.getId() + " failed");
}