Example usage for android.app.job JobInfo NETWORK_TYPE_ANY

List of usage examples for android.app.job JobInfo NETWORK_TYPE_ANY

Introduction

In this page you can find the example usage for android.app.job JobInfo NETWORK_TYPE_ANY.

Prototype

int NETWORK_TYPE_ANY

To view the source code for android.app.job JobInfo NETWORK_TYPE_ANY.

Click Source Link

Document

This job requires network connectivity.

Usage

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

public static void setUpPeriodicSync(Context context, String inputId) {
    PersistableBundle pBundle = new PersistableBundle();
    pBundle.putString(SyncJobService.BUNDLE_KEY_INPUT_ID, inputId);
    JobInfo.Builder builder = new JobInfo.Builder(PERIODIC_SYNC_JOB_ID,
            new ComponentName(context, SyncJobService.class));
    JobInfo jobInfo = builder.setExtras(pBundle).setPeriodic(SyncJobService.FULL_SYNC_FREQUENCY_MILLIS)
            .setPersisted(true).setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY).build();
    scheduleJob(context, jobInfo);/*from w w w. ja v a2s .co  m*/
}

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

public static void requestSync(Context context, String inputId, boolean currentProgramOnly) {
    PersistableBundle pBundle = new PersistableBundle();
    pBundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
    pBundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
    pBundle.putString(SyncJobService.BUNDLE_KEY_INPUT_ID, inputId);
    pBundle.putBoolean(SyncJobService.BUNDLE_KEY_CURRENT_PROGRAM_ONLY, currentProgramOnly);
    JobInfo.Builder builder = new JobInfo.Builder(REQUEST_SYNC_JOB_ID,
            new ComponentName(context, SyncJobService.class));
    JobInfo jobInfo = builder.setExtras(pBundle).setOverrideDeadline(SyncJobService.OVERRIDE_DEADLINE_MILLIS)
            .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY).build();
    scheduleJob(context, jobInfo);//w  w  w  . j a  va  2s .c o  m
    Intent intent = new Intent(SyncJobService.ACTION_SYNC_STATUS_CHANGED);
    intent.putExtra(SyncJobService.BUNDLE_KEY_INPUT_ID, inputId);
    intent.putExtra(SyncJobService.SYNC_STATUS, SyncJobService.SYNC_STARTED);
    LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}

From source file:io.github.hidroh.materialistic.data.SyncDelegate.java

@UiThread
public static void scheduleSync(Context context, Job job) {
    if (!Preferences.Offline.isEnabled(context)) {
        return;//from  w  w w .j  ava  2 s.  com
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && !TextUtils.isEmpty(job.id)) {
        JobInfo.Builder builder = new JobInfo.Builder(Long.valueOf(job.id).intValue(),
                new ComponentName(context.getPackageName(), ItemSyncJobService.class.getName()))
                        .setRequiredNetworkType(
                                Preferences.Offline.isWifiOnly(context) ? JobInfo.NETWORK_TYPE_UNMETERED
                                        : JobInfo.NETWORK_TYPE_ANY)
                        .setExtras(job.toPersistableBundle());
        if (Preferences.Offline.currentConnectionEnabled(context)) {
            builder.setOverrideDeadline(0);
        }
        ((JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE)).schedule(builder.build());
    } else {
        Bundle extras = new Bundle(job.toBundle());
        extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
        Account syncAccount;
        AccountManager accountManager = AccountManager.get(context);
        Account[] accounts = accountManager.getAccountsByType(BuildConfig.APPLICATION_ID);
        if (accounts.length == 0) {
            syncAccount = new Account(SYNC_ACCOUNT_NAME, BuildConfig.APPLICATION_ID);
            accountManager.addAccountExplicitly(syncAccount, null, null);
        } else {
            syncAccount = accounts[0];
        }
        ContentResolver.requestSync(syncAccount, MaterialisticProvider.PROVIDER_AUTHORITY, extras);
    }
}

From source file:com.google.android.car.kitchensink.job.JobSchedulerFragment.java

private void scheduleJob() {
    ComponentName jobComponentName = new ComponentName(getContext(), DishService.class);
    SharedPreferences prefs = getContext().getSharedPreferences(PREFS_NEXT_JOB_ID, Context.MODE_PRIVATE);
    int jobId = prefs.getInt(PREFS_NEXT_JOB_ID, 0);
    PersistableBundle bundle = new PersistableBundle();
    int count = 50;
    try {// www .j  ava 2 s. c o m
        count = Integer.valueOf(mDishNum.getText().toString());
    } catch (NumberFormatException e) {
        Log.e(TAG, "NOT A NUMBER!!!");
    }

    int selected = mNetworkGroup.getCheckedRadioButtonId();
    int networkType = JobInfo.NETWORK_TYPE_ANY;
    switch (selected) {
    case R.id.network_none:
        networkType = JobInfo.NETWORK_TYPE_NONE;
        break;
    case R.id.network_unmetered:
        networkType = JobInfo.NETWORK_TYPE_UNMETERED;
        break;
    case R.id.network_any:
        networkType = JobInfo.NETWORK_TYPE_ANY;
        break;
    }
    bundle.putInt(DishService.EXTRA_DISH_COUNT, count);
    JobInfo jobInfo = new JobInfo.Builder(jobId, jobComponentName)
            .setRequiresCharging(mRequireCharging.isChecked()).setRequiresDeviceIdle(mRequireIdle.isChecked())
            // TODO: figure out why we crash here even we hold
            // the RECEIVE_BOOT_COMPLETE permission
            //.setPersisted(mRequirePersisted.isChecked())
            .setExtras(bundle).setRequiredNetworkType(networkType).build();

    mJobScheduler.schedule(jobInfo);
    Toast.makeText(getContext(), "Scheduled: " + jobInfo, Toast.LENGTH_LONG).show();

    Log.d(TAG, "Scheduled a job: " + jobInfo);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putInt(PREFS_NEXT_JOB_ID, jobId + 1);
    editor.commit();

    refreshCurrentJobs();
}

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 {//  ww w  .  j ava  2  s.  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: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 .  ja  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:com.google.android.media.tv.companionlibrary.EpgSyncJobService.java

/**
 * Initializes a job that will periodically update the app's channels and programs.
 *
 * @param context Application's context.
 * @param inputId Component name for the app's TvInputService. This can be received through an
 * Intent extra parameter {@link TvInputInfo#EXTRA_INPUT_ID}.
 * @param jobServiceComponent The {@link EpgSyncJobService} component name that will run.
 * @param fullSyncPeriod The period between when the job will run a full background sync in
 * milliseconds.//from  w  w  w.  j  a v  a 2 s .c om
 * @param syncDuration The duration of EPG content to fetch in milliseconds. For a manual sync,
 * this should be relatively short. For a background sync this should be long.
 */
public static void setUpPeriodicSync(Context context, String inputId, ComponentName jobServiceComponent,
        long fullSyncPeriod, long syncDuration) {
    if (jobServiceComponent.getClass().isAssignableFrom(EpgSyncJobService.class)) {
        throw new IllegalArgumentException("This class does not extend EpgSyncJobService");
    }
    PersistableBundle persistableBundle = new PersistableBundle();
    persistableBundle.putString(EpgSyncJobService.BUNDLE_KEY_INPUT_ID, inputId);
    persistableBundle.putLong(EpgSyncJobService.BUNDLE_KEY_SYNC_PERIOD, syncDuration);
    JobInfo.Builder builder = new JobInfo.Builder(PERIODIC_SYNC_JOB_ID, jobServiceComponent);
    JobInfo jobInfo = builder.setExtras(persistableBundle).setPeriodic(fullSyncPeriod).setPersisted(true)
            .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY).build();
    scheduleJob(context, jobInfo);
    if (DEBUG) {
        Log.d(TAG, "Job has been scheduled for every " + fullSyncPeriod + "ms");
    }
}

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

/**
 * Retrieve the type of network connection required to schedule the last upload for an account
 * @param context//from w  w  w .ja  va 2  s  .co  m
 * @param accountName
 * @param remotePath to upload the file
 * @return 2 if only wifi is required, 1 if any internet connection is required (wifi or cellular)
 */
private int getRequiredNetworkType(Context context, String accountName, String remotePath) {

    UploadsStorageManager uploadsStorageManager = new UploadsStorageManager(context.getContentResolver());

    // Get last upload to be retried
    OCUpload ocUpload = uploadsStorageManager.getLastUploadFor(new OCFile(remotePath), accountName);

    PreferenceManager.CameraUploadsConfiguration mConfig = PreferenceManager
            .getCameraUploadsConfiguration(context);

    // Wifi by default
    int networkType = JobInfo.NETWORK_TYPE_UNMETERED;

    if (ocUpload != null && (ocUpload.getCreatedBy() == CREATED_AS_CAMERA_UPLOAD_PICTURE
            && !mConfig.isWifiOnlyForPictures()
            || ocUpload.getCreatedBy() == CREATED_AS_CAMERA_UPLOAD_VIDEO && !mConfig.isWifiOnlyForVideos())) {

        // Wifi or cellular
        networkType = JobInfo.NETWORK_TYPE_ANY;
    }

    return networkType;
}

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

/**
 * Manually requests a job to run now.//  www  .  j a v  a 2 s.  c  o m
 *
 * To check the current status of the sync, register a {@link android.content.BroadcastReceiver}
 * with an {@link android.content.IntentFilter} which checks for the action
 * {@link #ACTION_SYNC_STATUS_CHANGED}.
 * <p />
 * The sync status is an extra parameter in the {@link Intent} with key
 * {@link #SYNC_STATUS}. The sync status is either {@link #SYNC_STARTED} or
 * {@link #SYNC_FINISHED}.
 * <p />
 * Check that the value of {@link #BUNDLE_KEY_INPUT_ID} matches your
 * {@link android.media.tv.TvInputService}. If you're calling this from your setup activity,
 * you can get the extra parameter {@link TvInputInfo#EXTRA_INPUT_ID}.
 * <p />
 * @param context Application's context.
 * @param inputId Component name for the app's TvInputService. This can be received through an
 * Intent extra parameter {@link TvInputInfo#EXTRA_INPUT_ID}.
 * @param syncDuration The duration of EPG content to fetch in milliseconds. For a manual sync,
 * this should be relatively short. For a background sync this should be long.
 * @param jobServiceComponent The {@link EpgSyncJobService} class that will run.
 */
public static void requestImmediateSync(Context context, String inputId, long syncDuration,
        ComponentName jobServiceComponent) {
    if (jobServiceComponent.getClass().isAssignableFrom(EpgSyncJobService.class)) {
        throw new IllegalArgumentException("This class does not extend EpgSyncJobService");
    }
    PersistableBundle persistableBundle = new PersistableBundle();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
        persistableBundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
        persistableBundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
    }
    persistableBundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
    persistableBundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
    persistableBundle.putString(EpgSyncJobService.BUNDLE_KEY_INPUT_ID, inputId);
    persistableBundle.putLong(EpgSyncJobService.BUNDLE_KEY_SYNC_PERIOD, syncDuration);
    JobInfo.Builder builder = new JobInfo.Builder(REQUEST_SYNC_JOB_ID, jobServiceComponent);
    JobInfo jobInfo = builder.setExtras(persistableBundle)
            .setOverrideDeadline(EpgSyncJobService.OVERRIDE_DEADLINE_MILLIS)
            .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY).build();
    scheduleJob(context, jobInfo);
    if (DEBUG) {
        Log.d(TAG, "Single job scheduled");
    }
}