Example usage for android.content Context JOB_SCHEDULER_SERVICE

List of usage examples for android.content Context JOB_SCHEDULER_SERVICE

Introduction

In this page you can find the example usage for android.content Context JOB_SCHEDULER_SERVICE.

Prototype

String JOB_SCHEDULER_SERVICE

To view the source code for android.content Context JOB_SCHEDULER_SERVICE.

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.app.job.JobScheduler instance for managing occasional background tasks.

Usage

From source file:com.android.contacts.DynamicShortcuts.java

public DynamicShortcuts(Context context) {
    this(context, context.getContentResolver(),
            (ShortcutManager) context.getSystemService(Context.SHORTCUT_SERVICE),
            (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE));
}

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  w ww.  ja  va2  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");
}

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) {//ww w.j a va2 s  .  co  m
        Log.d(TAG, "Scheduling result is " + result);
    }
}

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);//from  w  ww .j a  va2s. c o  m
    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: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./*  w  ww . j a  va 2 s. co  m*/
 *
 * @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:com.google.android.media.tv.companionlibrary.EpgSyncJobService.java

/**
 * Cancels all pending jobs./*from  ww w .ja v  a2 s  . c  o m*/
 * @param context Application's context.
 */
public static void cancelAllSyncRequests(Context context) {
    JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
    jobScheduler.cancelAll();
}

From source file:com.android.contacts.DynamicShortcuts.java

@VisibleForTesting
public static void reset(Context context) {
    final JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
    jobScheduler.cancel(ContactsJobService.DYNAMIC_SHORTCUTS_JOB_ID);

    if (!CompatUtils.isLauncherShortcutCompatible()) {
        return;/*w  ww  .j  a  v  a 2  s. c o m*/
    }
    new DynamicShortcuts(context).removeAllShortcuts();
}

From source file:com.android.contacts.DynamicShortcuts.java

@VisibleForTesting
public static boolean isJobScheduled(Context context) {
    final JobScheduler scheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
    return scheduler.getPendingJob(ContactsJobService.DYNAMIC_SHORTCUTS_JOB_ID) != null;
}