Java Code Examples for android.os.PersistableBundle#putInt()

The following examples show how to use android.os.PersistableBundle#putInt() . 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: AndroidJobSchedulerUtils.java    From android_job_scheduler with Apache License 2.0 6 votes vote down vote up
public static PersistableBundle serializedDataToPersistableBundle(List<?> args, Context context) {
    final ComponentName name = new ComponentName(context, AndroidJobScheduler.class);
    final Integer every = (Integer) args.get(0);
    final String funcCallback = (String) args.get(1);
    final Integer id = (Integer) args.get(2);
    final Map<String, Map<String, Object>> constraints = (Map<String, Map<String, Object>>) args.get(3);
    PersistableBundle job = new PersistableBundle();
    job.putString(B_KEY_RESCHEDULE, funcCallback);
    job.putInt(B_KEY_ID, id);
    job.putInt(B_KEY_INTERVAL, every);
    job.putString(B_KEY_DART_CB, funcCallback);
    job.putString(B_KEY_COMPONENT_PKG, name.getPackageName());
    job.putString(B_KEY_COMPONENT_NAME, name.getClassName());
    if (constraints != null) {
        for (Map.Entry<String, Map<String, Object>> entry : constraints.entrySet()) {
            PersistableBundle innerBundle = new PersistableBundle();
            for (Map.Entry<String, Object> innerEntry : entry.getValue().entrySet()) {
                innerBundle.putInt(innerEntry.getKey(), (Integer) innerEntry.getValue());
            }
            job.putPersistableBundle(entry.getKey(), innerBundle);
        }
    }
    return job;
}
 
Example 2
Source File: PlatformScheduler.java    From Telegram-FOSS with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("MissingPermission")
private static JobInfo buildJobInfo(
    int jobId,
    ComponentName jobServiceComponentName,
    Requirements requirements,
    String serviceAction,
    String servicePackage) {
  JobInfo.Builder builder = new JobInfo.Builder(jobId, jobServiceComponentName);

  if (requirements.isUnmeteredNetworkRequired()) {
    builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED);
  } else if (requirements.isNetworkRequired()) {
    builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
  }
  builder.setRequiresDeviceIdle(requirements.isIdleRequired());
  builder.setRequiresCharging(requirements.isChargingRequired());
  builder.setPersisted(true);

  PersistableBundle extras = new PersistableBundle();
  extras.putString(KEY_SERVICE_ACTION, serviceAction);
  extras.putString(KEY_SERVICE_PACKAGE, servicePackage);
  extras.putInt(KEY_REQUIREMENTS, requirements.getRequirements());
  builder.setExtras(extras);

  return builder.build();
}
 
Example 3
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 4
Source File: BundleUtil.java    From android-testdpc with Apache License 2.0 6 votes vote down vote up
@TargetApi(VERSION_CODES.LOLLIPOP_MR1)
public static PersistableBundle bundleToPersistableBundle(Bundle bundle) {
    Set<String> keySet = bundle.keySet();
    PersistableBundle persistableBundle = new PersistableBundle();
    for (String key : keySet) {
        Object value = bundle.get(key);
        if (value instanceof Boolean) {
            persistableBundle.putBoolean(key, (boolean) value);
        } else if (value instanceof Integer) {
            persistableBundle.putInt(key, (int) value);
        } else if (value instanceof String) {
            persistableBundle.putString(key, (String) value);
        } else if (value instanceof String[]) {
            persistableBundle.putStringArray(key, (String[]) value);
        } else if (value instanceof Bundle) {
            PersistableBundle innerBundle = bundleToPersistableBundle((Bundle) value);
            persistableBundle.putPersistableBundle(key, innerBundle);
        }
    }
    return persistableBundle;
}
 
Example 5
Source File: NotificationJobService.java    From 365browser with Apache License 2.0 6 votes vote down vote up
static PersistableBundle getJobExtrasFromIntent(Intent intent) {
    PersistableBundle bundle = new PersistableBundle();
    bundle.putString(NotificationConstants.EXTRA_NOTIFICATION_ID,
            intent.getStringExtra(NotificationConstants.EXTRA_NOTIFICATION_ID));
    bundle.putString(NotificationConstants.EXTRA_NOTIFICATION_INFO_ORIGIN,
            intent.getStringExtra(NotificationConstants.EXTRA_NOTIFICATION_INFO_ORIGIN));
    bundle.putString(NotificationConstants.EXTRA_NOTIFICATION_INFO_PROFILE_ID,
            intent.getStringExtra(NotificationConstants.EXTRA_NOTIFICATION_INFO_PROFILE_ID));
    bundle.putBoolean(NotificationConstants.EXTRA_NOTIFICATION_INFO_PROFILE_INCOGNITO,
            intent.getBooleanExtra(
                    NotificationConstants.EXTRA_NOTIFICATION_INFO_PROFILE_INCOGNITO, false));
    bundle.putString(NotificationConstants.EXTRA_NOTIFICATION_INFO_TAG,
            intent.getStringExtra(NotificationConstants.EXTRA_NOTIFICATION_INFO_TAG));
    bundle.putInt(NotificationConstants.EXTRA_NOTIFICATION_INFO_ACTION_INDEX,
            intent.getIntExtra(NotificationConstants.EXTRA_NOTIFICATION_INFO_ACTION_INDEX, -1));
    bundle.putString(NotificationConstants.EXTRA_NOTIFICATION_INFO_WEBAPK_PACKAGE,
            intent.getStringExtra(
                    NotificationConstants.EXTRA_NOTIFICATION_INFO_WEBAPK_PACKAGE));
    bundle.putString(NotificationConstants.EXTRA_NOTIFICATION_ACTION, intent.getAction());
    // Only primitives can be set on a persistable bundle, so extract the raw reply.
    bundle.putString(NotificationConstants.EXTRA_NOTIFICATION_REPLY,
            NotificationPlatformBridge.getNotificationReply(intent));
    return bundle;
}
 
Example 6
Source File: PlatformScheduler.java    From Telegram with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("MissingPermission")
private static JobInfo buildJobInfo(
    int jobId,
    ComponentName jobServiceComponentName,
    Requirements requirements,
    String serviceAction,
    String servicePackage) {
  JobInfo.Builder builder = new JobInfo.Builder(jobId, jobServiceComponentName);

  if (requirements.isUnmeteredNetworkRequired()) {
    builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED);
  } else if (requirements.isNetworkRequired()) {
    builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
  }
  builder.setRequiresDeviceIdle(requirements.isIdleRequired());
  builder.setRequiresCharging(requirements.isChargingRequired());
  builder.setPersisted(true);

  PersistableBundle extras = new PersistableBundle();
  extras.putString(KEY_SERVICE_ACTION, serviceAction);
  extras.putString(KEY_SERVICE_PACKAGE, servicePackage);
  extras.putInt(KEY_REQUIREMENTS, requirements.getRequirements());
  builder.setExtras(extras);

  return builder.build();
}
 
Example 7
Source File: RefreshScheduler.java    From mimi-reader with Apache License 2.0 6 votes vote down vote up
private void scheduleJob(ThreadInfo threadInfo, long nextRunTime) {
    long delay = nextRunTime - System.currentTimeMillis();
    PersistableBundle bundle = new PersistableBundle();
    bundle.putLong(THREAD_ID_EXTRA, threadInfo.threadId);
    bundle.putString(BOARD_NAME_EXTRA, threadInfo.boardName);
    bundle.putString(BOARD_TITLE_EXTRA, threadInfo.boardTitle);
    bundle.putInt(WATCHED_EXTRA, threadInfo.watched ? 1 : 0);
    bundle.putLong(LAST_REFRESH_TIME_EXTRA, threadInfo.refreshTimestamp);
    bundle.putInt(RESULT_KEY, RESULT_SCHEDULED);
    bundle.putInt(BACKGROUNDED_KEY, backgrounded ? 1 : 0);

    ComponentName serviceComponent = new ComponentName(context, RefreshJobService.class);
    JobInfo jobInfo = new JobInfo.Builder(JOB_ID, serviceComponent)
            .setMinimumLatency(delay)
            .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
            .setRequiresCharging(false)
            .setExtras(bundle)
            .build();
    refreshScheduler.schedule(jobInfo);
}
 
Example 8
Source File: PlatformScheduler.java    From MediaSDK with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("MissingPermission")
private static JobInfo buildJobInfo(
    int jobId,
    ComponentName jobServiceComponentName,
    Requirements requirements,
    String serviceAction,
    String servicePackage) {
  JobInfo.Builder builder = new JobInfo.Builder(jobId, jobServiceComponentName);

  if (requirements.isUnmeteredNetworkRequired()) {
    builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED);
  } else if (requirements.isNetworkRequired()) {
    builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
  }
  builder.setRequiresDeviceIdle(requirements.isIdleRequired());
  builder.setRequiresCharging(requirements.isChargingRequired());
  builder.setPersisted(true);

  PersistableBundle extras = new PersistableBundle();
  extras.putString(KEY_SERVICE_ACTION, serviceAction);
  extras.putString(KEY_SERVICE_PACKAGE, servicePackage);
  extras.putInt(KEY_REQUIREMENTS, requirements.getRequirements());
  builder.setExtras(extras);

  return builder.build();
}
 
Example 9
Source File: Location.java    From your-local-weather with GNU General Public License v3.0 6 votes vote down vote up
public PersistableBundle getPersistableBundle() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        PersistableBundle persistableBundle = new PersistableBundle();
        persistableBundle.putLong("id", id);
        persistableBundle.putDouble("latitude", latitude);
        persistableBundle.putDouble("longitude", longitude);
        persistableBundle.putInt("orderId", orderId);
        persistableBundle.putString("locale", localeAbbrev);
        persistableBundle.putString("nickname", nickname);
        persistableBundle.putDouble("accuracy", new Double(accuracy));
        persistableBundle.putString("locationSource", locationSource);
        persistableBundle.putLong("lastLocationUpdate", lastLocationUpdate);
        persistableBundle.putPersistableBundle("address", PersistableBundleBuilder.fromAddress(address));
        return persistableBundle;
    } else {
        return null;
    }
}
 
Example 10
Source File: myJobService.java    From service with Apache License 2.0 5 votes vote down vote up
public static void scheduleJob(Context context, int max, boolean recurring) {

        ComponentName serviceComponent = new ComponentName(context, myJobService.class);
        JobInfo.Builder builder = new JobInfo.Builder(0, serviceComponent);

        if (recurring) {
            builder.setPeriodic(15* 10000); //only once every 15 seconds.
            //builder.setPersisted(true);  //will persist across reboots.
            //except this runs in about 10 to 30 minute intervals...  Likely a min threshold here.
            Log.wtf(TAG, "set recurring");
        } else {  //just set it for once, between 10 to 30 seconds from now.
            builder.setMinimumLatency(10 * 1000); // wait at least
            builder.setOverrideDeadline(30 * 1000); // maximum delay
            Log.wtf(TAG, "set once");
        }

        //builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED); // require unmetered network
        //builder.setRequiresDeviceIdle(true); // device should be idle
        //builder.setRequiresCharging(false); // we don't care if the device is charging or not
        //builder.setRequiresBatteryNotLow(true);  //only when the batter is not low.  API 26+
        //set some data via a persistablebundle.
        PersistableBundle extras = new PersistableBundle();
        extras.putInt("max", max);
        builder.setExtras(extras);

        JobScheduler jobScheduler = (JobScheduler) context.getSystemService(JobScheduler.class);
        jobScheduler.schedule(builder.build());
    }
 
Example 11
Source File: VoiceSettingParameter.java    From your-local-weather with GNU General Public License v3.0 5 votes vote down vote up
public PersistableBundle getPersistableBundle() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        PersistableBundle persistableBundle = new PersistableBundle();
        persistableBundle.putLong("id", id);
        persistableBundle.putLong("voiceSettingId", voiceSettingId);
        persistableBundle.putInt("paramTypeId", paramTypeId);
        persistableBundle.putInt("paramBooleanValue", mapBooleanToInt(paramBooleanValue));
        persistableBundle.putLong("paramLongValue", paramLongValue);
        persistableBundle.putString("paramStringValue", paramStringValue);
        return persistableBundle;
    } else {
        return null;
    }
}
 
Example 12
Source File: SyncDelegate.java    From materialistic with Apache License 2.0 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Synthetic PersistableBundle toPersistableBundle() {
    PersistableBundle bundle = new PersistableBundle();
    bundle.putString(EXTRA_ID, id);
    bundle.putInt(EXTRA_CONNECTION_ENABLED, connectionEnabled ? 1 : 0);
    bundle.putInt(EXTRA_READABILITY_ENABLED, readabilityEnabled ? 1 : 0);
    bundle.putInt(EXTRA_ARTICLE_ENABLED, articleEnabled ? 1 : 0);
    bundle.putInt(EXTRA_COMMENTS_ENABLED, commentsEnabled ? 1 : 0);
    bundle.putInt(EXTRA_NOTIFICATION_ENABLED, notificationEnabled ? 1 : 0);
    return bundle;
}
 
Example 13
Source File: BundleToPersistableBundleConverter.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Copy all entries in the {@link Bundle} that can be part of a {@link PersistableBundle}.
 *
 * @param bundle the {@link Bundle} to convert.
 * @return a result object contain the resulting {@link PersistableBundle} and whether any of
 *         the keys failed.
 */
static Result convert(Bundle bundle) {
    PersistableBundle persistableBundle = new PersistableBundle();
    Set<String> failedKeys = new HashSet<>();
    for (String key : bundle.keySet()) {
        Object obj = bundle.get(key);
        if (obj == null) {
            persistableBundle.putString(key, null);
        } else if (obj instanceof Boolean) {
            persistableBundle.putBoolean(key, (Boolean) obj);
        } else if (obj instanceof boolean[]) {
            persistableBundle.putBooleanArray(key, (boolean[]) obj);
        } else if (obj instanceof Double) {
            persistableBundle.putDouble(key, (Double) obj);
        } else if (obj instanceof double[]) {
            persistableBundle.putDoubleArray(key, (double[]) obj);
        } else if (obj instanceof Integer) {
            persistableBundle.putInt(key, (Integer) obj);
        } else if (obj instanceof int[]) {
            persistableBundle.putIntArray(key, (int[]) obj);
        } else if (obj instanceof Long) {
            persistableBundle.putLong(key, (Long) obj);
        } else if (obj instanceof long[]) {
            persistableBundle.putLongArray(key, (long[]) obj);
        } else if (obj instanceof String) {
            persistableBundle.putString(key, (String) obj);
        } else if (obj instanceof String[]) {
            persistableBundle.putStringArray(key, (String[]) obj);
        } else {
            failedKeys.add(key);
        }
    }
    return new Result(persistableBundle, failedKeys);
}
 
Example 14
Source File: DocumentCentricActivity.java    From user-interface-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
    /*
    To maintain activity state across reboots the system saves and restore critical information for
    all tasks and their activities. Information known by the system includes the activity stack order,
    each task’s thumbnails and each activity’s and task's Intents. For Information that cannot be retained
    because they contain Bundles which can’t be persisted a new constrained version of Bundle,
    PersistableBundle is added. PersistableBundle can store only basic data types. To use it
    in your Activities you must declare the new activity:persistableMode attribute in the manifest.
     */
    outPersistentState.putInt(KEY_EXTRA_NEW_DOCUMENT_COUNTER, mDocumentCounter);
    super.onSaveInstanceState(outState, outPersistentState);
}
 
Example 15
Source File: DocumentCentricActivity.java    From android-DocumentCentricApps with Apache License 2.0 5 votes vote down vote up
@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
    /*
    To maintain activity state across reboots the system saves and restore critical information for
    all tasks and their activities. Information known by the system includes the activity stack order,
    each task’s thumbnails and each activity’s and task's Intents. For Information that cannot be retained
    because they contain Bundles which can’t be persisted a new constrained version of Bundle,
    PersistableBundle is added. PersistableBundle can store only basic data types. To use it
    in your Activities you must declare the new activity:persistableMode attribute in the manifest.
     */
    outPersistentState.putInt(KEY_EXTRA_NEW_DOCUMENT_COUNTER, mDocumentCounter);
    super.onSaveInstanceState(outState, outPersistentState);
}
 
Example 16
Source File: SystemUpdateManagerService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private void saveSystemUpdateInfoLocked(PersistableBundle infoBundle, int uid) {
    // Wrap the incoming bundle with extra info (e.g. version, uid, boot count). We use nested
    // PersistableBundle to avoid manually parsing XML attributes when loading the info back.
    PersistableBundle outBundle = new PersistableBundle();
    outBundle.putPersistableBundle(KEY_INFO_BUNDLE, infoBundle);
    outBundle.putInt(KEY_VERSION, INFO_FILE_VERSION);
    outBundle.putInt(KEY_UID, uid);
    outBundle.putInt(KEY_BOOT_COUNT, getBootCount());

    // Only update the info on success.
    if (writeInfoFileLocked(outBundle)) {
        mLastUid = uid;
        mLastStatus = infoBundle.getInt(KEY_STATUS);
    }
}
 
Example 17
Source File: PlatformScheduler.java    From TelePlus-Android with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("MissingPermission")
private static JobInfo buildJobInfo(
    int jobId,
    ComponentName jobServiceComponentName,
    Requirements requirements,
    String serviceAction,
    String servicePackage) {
  JobInfo.Builder builder = new JobInfo.Builder(jobId, jobServiceComponentName);

  int networkType;
  switch (requirements.getRequiredNetworkType()) {
    case Requirements.NETWORK_TYPE_NONE:
      networkType = JobInfo.NETWORK_TYPE_NONE;
      break;
    case Requirements.NETWORK_TYPE_ANY:
      networkType = JobInfo.NETWORK_TYPE_ANY;
      break;
    case Requirements.NETWORK_TYPE_UNMETERED:
      networkType = JobInfo.NETWORK_TYPE_UNMETERED;
      break;
    case Requirements.NETWORK_TYPE_NOT_ROAMING:
      if (Util.SDK_INT >= 24) {
        networkType = JobInfo.NETWORK_TYPE_NOT_ROAMING;
      } else {
        throw new UnsupportedOperationException();
      }
      break;
    case Requirements.NETWORK_TYPE_METERED:
      if (Util.SDK_INT >= 26) {
        networkType = JobInfo.NETWORK_TYPE_METERED;
      } else {
        throw new UnsupportedOperationException();
      }
      break;
    default:
      throw new UnsupportedOperationException();
  }

  builder.setRequiredNetworkType(networkType);
  builder.setRequiresDeviceIdle(requirements.isIdleRequired());
  builder.setRequiresCharging(requirements.isChargingRequired());
  builder.setPersisted(true);

  PersistableBundle extras = new PersistableBundle();
  extras.putString(KEY_SERVICE_ACTION, serviceAction);
  extras.putString(KEY_SERVICE_PACKAGE, servicePackage);
  extras.putInt(KEY_REQUIREMENTS, requirements.getRequirementsData());
  builder.setExtras(extras);

  return builder.build();
}
 
Example 18
Source File: JobInfoScheduler.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
/**
 * Schedules the JobScheduler service.
 *
 * @param transportContext Contains information about the backend and the priority.
 * @param attemptNumber Number of times the JobScheduler has tried to log for this backend.
 */
@Override
public void schedule(TransportContext transportContext, int attemptNumber) {
  ComponentName serviceComponent = new ComponentName(context, JobInfoSchedulerService.class);
  JobScheduler jobScheduler =
      (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
  int jobId = getJobId(transportContext);
  // Check if there exists a job scheduled for this backend name.
  if (isJobServiceOn(jobScheduler, jobId, attemptNumber)) {
    Logging.d(
        LOG_TAG, "Upload for context %s is already scheduled. Returning...", transportContext);
    return;
  }

  long nextCallTime = eventStore.getNextCallTime(transportContext);

  // Schedule the build.
  JobInfo.Builder builder =
      config.configureJob(
          new JobInfo.Builder(jobId, serviceComponent),
          transportContext.getPriority(),
          nextCallTime,
          attemptNumber);

  PersistableBundle bundle = new PersistableBundle();
  bundle.putInt(ATTEMPT_NUMBER, attemptNumber);
  bundle.putString(BACKEND_NAME, transportContext.getBackendName());
  bundle.putInt(EVENT_PRIORITY, PriorityMapping.toInt(transportContext.getPriority()));
  if (transportContext.getExtras() != null) {
    bundle.putString(EXTRAS, encodeToString(transportContext.getExtras(), DEFAULT));
  }
  builder.setExtras(bundle);

  Logging.d(
      LOG_TAG,
      "Scheduling upload for context %s with jobId=%d in %dms(Backend next call timestamp %d). Attempt %d",
      transportContext,
      jobId,
      config.getScheduleDelay(transportContext.getPriority(), nextCallTime, attemptNumber),
      nextCallTime,
      attemptNumber);

  jobScheduler.schedule(builder.build());
}
 
Example 19
Source File: PlatformScheduler.java    From TelePlus-Android with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("MissingPermission")
private static JobInfo buildJobInfo(
    int jobId,
    ComponentName jobServiceComponentName,
    Requirements requirements,
    String serviceAction,
    String servicePackage) {
  JobInfo.Builder builder = new JobInfo.Builder(jobId, jobServiceComponentName);

  int networkType;
  switch (requirements.getRequiredNetworkType()) {
    case Requirements.NETWORK_TYPE_NONE:
      networkType = JobInfo.NETWORK_TYPE_NONE;
      break;
    case Requirements.NETWORK_TYPE_ANY:
      networkType = JobInfo.NETWORK_TYPE_ANY;
      break;
    case Requirements.NETWORK_TYPE_UNMETERED:
      networkType = JobInfo.NETWORK_TYPE_UNMETERED;
      break;
    case Requirements.NETWORK_TYPE_NOT_ROAMING:
      if (Util.SDK_INT >= 24) {
        networkType = JobInfo.NETWORK_TYPE_NOT_ROAMING;
      } else {
        throw new UnsupportedOperationException();
      }
      break;
    case Requirements.NETWORK_TYPE_METERED:
      if (Util.SDK_INT >= 26) {
        networkType = JobInfo.NETWORK_TYPE_METERED;
      } else {
        throw new UnsupportedOperationException();
      }
      break;
    default:
      throw new UnsupportedOperationException();
  }

  builder.setRequiredNetworkType(networkType);
  builder.setRequiresDeviceIdle(requirements.isIdleRequired());
  builder.setRequiresCharging(requirements.isChargingRequired());
  builder.setPersisted(true);

  PersistableBundle extras = new PersistableBundle();
  extras.putString(KEY_SERVICE_ACTION, serviceAction);
  extras.putString(KEY_SERVICE_PACKAGE, servicePackage);
  extras.putInt(KEY_REQUIREMENTS, requirements.getRequirementsData());
  builder.setExtras(extras);

  return builder.build();
}
 
Example 20
Source File: SyncOperation.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
/**
 * All fields are stored in a corresponding key in the persistable bundle.
 *
 * {@link #extras} is a Bundle and can contain parcelable objects. But only the type Account
 * is allowed {@link ContentResolver#validateSyncExtrasBundle(Bundle)} that can't be stored in
 * a PersistableBundle. For every value of type Account with key 'key', we store a
 * PersistableBundle containing account information at key 'ACCOUNT:key'. The Account object
 * can be reconstructed using this.
 *
 * We put a flag with key 'SyncManagerJob', to identify while reconstructing a sync operation
 * from a bundle whether the bundle actually contains information about a sync.
 * @return A persistable bundle containing all information to re-construct the sync operation.
 */
PersistableBundle toJobInfoExtras() {
    // This will be passed as extras bundle to a JobScheduler job.
    PersistableBundle jobInfoExtras = new PersistableBundle();

    PersistableBundle syncExtrasBundle = new PersistableBundle();
    for (String key: extras.keySet()) {
        Object value = extras.get(key);
        if (value instanceof Account) {
            Account account = (Account) value;
            PersistableBundle accountBundle = new PersistableBundle();
            accountBundle.putString("accountName", account.name);
            accountBundle.putString("accountType", account.type);
            // This is stored in jobInfoExtras so that we don't override a user specified
            // sync extra with the same key.
            jobInfoExtras.putPersistableBundle("ACCOUNT:" + key, accountBundle);
        } else if (value instanceof Long) {
            syncExtrasBundle.putLong(key, (Long) value);
        } else if (value instanceof Integer) {
            syncExtrasBundle.putInt(key, (Integer) value);
        } else if (value instanceof Boolean) {
            syncExtrasBundle.putBoolean(key, (Boolean) value);
        } else if (value instanceof Float) {
            syncExtrasBundle.putDouble(key, (double) (float) value);
        } else if (value instanceof Double) {
            syncExtrasBundle.putDouble(key, (Double) value);
        } else if (value instanceof String) {
            syncExtrasBundle.putString(key, (String) value);
        } else if (value == null) {
            syncExtrasBundle.putString(key, null);
        } else {
            Slog.e(TAG, "Unknown extra type.");
        }
    }
    jobInfoExtras.putPersistableBundle("syncExtras", syncExtrasBundle);

    jobInfoExtras.putBoolean("SyncManagerJob", true);

    jobInfoExtras.putString("provider", target.provider);
    jobInfoExtras.putString("accountName", target.account.name);
    jobInfoExtras.putString("accountType", target.account.type);
    jobInfoExtras.putInt("userId", target.userId);
    jobInfoExtras.putInt("owningUid", owningUid);
    jobInfoExtras.putString("owningPackage", owningPackage);
    jobInfoExtras.putInt("reason", reason);
    jobInfoExtras.putInt("source", syncSource);
    jobInfoExtras.putBoolean("allowParallelSyncs", allowParallelSyncs);
    jobInfoExtras.putInt("jobId", jobId);
    jobInfoExtras.putBoolean("isPeriodic", isPeriodic);
    jobInfoExtras.putInt("sourcePeriodicId", sourcePeriodicId);
    jobInfoExtras.putLong("periodMillis", periodMillis);
    jobInfoExtras.putLong("flexMillis", flexMillis);
    jobInfoExtras.putLong("expectedRuntime", expectedRuntime);
    jobInfoExtras.putInt("retries", retries);
    jobInfoExtras.putInt("syncExemptionFlag", syncExemptionFlag);
    return jobInfoExtras;
}