Example usage for android.app.job JobInfo NETWORK_TYPE_UNMETERED

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

Introduction

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

Prototype

int NETWORK_TYPE_UNMETERED

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

Click Source Link

Document

This job requires network connectivity that is unmetered.

Usage

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 a v  a  2 s .  co m
    }
    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 {/*from  w  w  w . j  a v  a2  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: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;//w  w w  . jav  a  2  s  .  c  o 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: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 ww  w.  j  av  a  2s .  com
    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

/**
 * Retrieve the type of network connection required to schedule the last upload for an account
 * @param context/*www.  j  a va2 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;
}