androidx.work.BackoffPolicy Java Examples

The following examples show how to use androidx.work.BackoffPolicy. 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: DataSyncWorkManager.java    From ground-android with Apache License 2.0 7 votes vote down vote up
private OneTimeWorkRequest buildWorkerRequest(String featureId) {
  return new OneTimeWorkRequest.Builder(LocalMutationSyncWorker.class)
      .setConstraints(getWorkerConstraints())
      .setBackoffCriteria(BackoffPolicy.LINEAR, SYNC_BACKOFF_MILLIS, TimeUnit.MILLISECONDS)
      .setInputData(LocalMutationSyncWorker.createInputData(featureId))
      .build();
}
 
Example #2
Source File: FlutterDownloaderPlugin.java    From flutter_downloader with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
private WorkRequest buildRequest(String url, String savedDir, String filename, String headers, boolean showNotification, boolean openFileFromNotification, boolean isResume, boolean requiresStorageNotLow) {
    WorkRequest request = new OneTimeWorkRequest.Builder(DownloadWorker.class)
            .setConstraints(new Constraints.Builder()
                    .setRequiresStorageNotLow(requiresStorageNotLow)
                    .setRequiredNetworkType(NetworkType.CONNECTED)
                    .build())
            .addTag(TAG)
            .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 5, TimeUnit.SECONDS)
            .setInputData(new Data.Builder()
                    .putString(DownloadWorker.ARG_URL, url)
                    .putString(DownloadWorker.ARG_SAVED_DIR, savedDir)
                    .putString(DownloadWorker.ARG_FILE_NAME, filename)
                    .putString(DownloadWorker.ARG_HEADERS, headers)
                    .putBoolean(DownloadWorker.ARG_SHOW_NOTIFICATION, showNotification)
                    .putBoolean(DownloadWorker.ARG_OPEN_FILE_FROM_NOTIFICATION, openFileFromNotification)
                    .putBoolean(DownloadWorker.ARG_IS_RESUME, isResume)
                    .putLong(DownloadWorker.ARG_CALLBACK_HANDLE, callbackHandle)
                    .putBoolean(DownloadWorker.ARG_DEBUG, debugMode == 1)
                    .build()
            )
            .build();
    return request;
}
 
Example #3
Source File: WorkerHelper.java    From GeometricWeather with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void setNormalPollingWork(Context context, float pollingRate) {
    PeriodicWorkRequest request = new PeriodicWorkRequest.Builder(
            NormalUpdateWorker.class,
            (long) (pollingRate * MINUTES_PER_HOUR),
            TimeUnit.MINUTES
    ).setBackoffCriteria(
            BackoffPolicy.LINEAR,
            BACKOFF_DELAY_MINUTES,
            TimeUnit.MINUTES
    ).setConstraints(
            new Constraints.Builder()
                    .setRequiredNetworkType(NetworkType.CONNECTED)
                    .build()
    ).build();

    WorkManager.getInstance(context).enqueueUniquePeriodicWork(
            WORK_NAME_NORMAL_VIEW,
            ExistingPeriodicWorkPolicy.KEEP,
            request
    );
}
 
Example #4
Source File: CommCareApplication.java    From commcare-android with Apache License 2.0 6 votes vote down vote up
private void scheduleFormSubmissions() {
    Constraints constraints = new Constraints.Builder()
            .setRequiredNetworkType(NetworkType.CONNECTED)
            .setRequiresBatteryNotLow(true)
            .build();

    PeriodicWorkRequest formSubmissionRequest =
            new PeriodicWorkRequest.Builder(FormSubmissionWorker.class, PERIODICITY_FOR_FORM_SUBMISSION_IN_HOURS, TimeUnit.HOURS)
                    .addTag(getCurrentApp().getAppRecord().getApplicationId())
                    .setConstraints(constraints)
                    .setBackoffCriteria(
                            BackoffPolicy.EXPONENTIAL,
                            BACKOFF_DELAY_FOR_FORM_SUBMISSION_RETRY,
                            TimeUnit.MILLISECONDS)
                    .build();

    WorkManager.getInstance(this).enqueueUniquePeriodicWork(
            FormSubmissionHelper.getFormSubmissionRequestName(getCurrentApp().getUniqueId()),
            ExistingPeriodicWorkPolicy.KEEP,
            formSubmissionRequest
    );
}
 
Example #5
Source File: CommCareApplication.java    From commcare-android with Apache License 2.0 6 votes vote down vote up
private void scheduleAppUpdate() {
    if (UpdateHelper.shouldAutoUpdate()) {
        Constraints constraints = new Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED)
                .setRequiresBatteryNotLow(true)
                .build();


        PeriodicWorkRequest updateRequest =
                new PeriodicWorkRequest.Builder(UpdateWorker.class, UpdateHelper.getAutoUpdatePeriodicity(), TimeUnit.HOURS)
                        .addTag(getCurrentApp().getAppRecord().getApplicationId())
                        .setConstraints(constraints)
                        .setBackoffCriteria(
                                BackoffPolicy.EXPONENTIAL,
                                BACKOFF_DELAY_FOR_UPDATE_RETRY,
                                TimeUnit.MILLISECONDS)
                        .build();

        WorkManager.getInstance(this).enqueueUniquePeriodicWork(
                UpdateHelper.getUpdateRequestName(),
                ExistingPeriodicWorkPolicy.KEEP,
                updateRequest
        );
    }
}
 
Example #6
Source File: FlutterUploaderPlugin.java    From flutter_uploader with MIT License 5 votes vote down vote up
private WorkRequest buildRequest(UploadTask task) {
  Gson gson = new Gson();

  Data.Builder dataBuilder =
      new Data.Builder()
          .putString(UploadWorker.ARG_URL, task.getURL())
          .putString(UploadWorker.ARG_METHOD, task.getMethod())
          .putInt(UploadWorker.ARG_REQUEST_TIMEOUT, task.getTimeout())
          .putBoolean(UploadWorker.ARG_SHOW_NOTIFICATION, task.canShowNotification())
          .putBoolean(UploadWorker.ARG_BINARY_UPLOAD, task.isBinaryUpload())
          .putString(UploadWorker.ARG_UPLOAD_REQUEST_TAG, task.getTag())
          .putInt(UploadWorker.ARG_ID, task.getId());

  List<FileItem> files = task.getFiles();

  String fileItemsJson = gson.toJson(files);
  dataBuilder.putString(UploadWorker.ARG_FILES, fileItemsJson);

  if (task.getHeaders() != null) {
    String headersJson = gson.toJson(task.getHeaders());
    dataBuilder.putString(UploadWorker.ARG_HEADERS, headersJson);
  }

  if (task.getParameters() != null) {
    String parametersJson = gson.toJson(task.getParameters());
    dataBuilder.putString(UploadWorker.ARG_DATA, parametersJson);
  }

  return new OneTimeWorkRequest.Builder(UploadWorker.class)
      .setConstraints(
          new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
      .addTag(TAG)
      .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 5, TimeUnit.SECONDS)
      .setInputData(dataBuilder.build())
      .build();
}
 
Example #7
Source File: PixelWatchFace.java    From PixelWatchFace with GNU General Public License v3.0 1 votes vote down vote up
private void initWeatherUpdater(boolean forceUpdate) {
  String TAG = "initWeatherUpdater";
  if (!mSettings.isWeatherDisabled()) {
    if (ActivityCompat
        .checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION)
        != PackageManager.PERMISSION_GRANTED) {
      Log.d(TAG, "requesting permission");
      requestPermissions();
    } else {
      Log.d(TAG, "last weather retrieved: " + mCurrentWeather.getTime());
      Log.d(TAG, "current time: " + System.currentTimeMillis());

      Constraints constraints = new Constraints.Builder()
          .setRequiredNetworkType(NetworkType.CONNECTED)
          .build();

      if (forceUpdate || mWeatherRequestedTime == 0
          || System.currentTimeMillis() - mWeatherRequestedTime >= TimeUnit.MINUTES
          .toMillis(WEATHER_UPDATE_INTERVAL)) {

        OneTimeWorkRequest locationUpdate =
            new OneTimeWorkRequest.Builder(LocationUpdateWorker.class)
                .setConstraints(constraints)
                // forced weather update is expected to happen sooner, so
                // try again in (30 seconds * attempt count). After 3 failed
                // attempts, it would wait 1.5 minutes before retrying again
                .setBackoffCriteria(BackoffPolicy.LINEAR, WEATHER_BACKOFF_DELAY_ONETIME,
                    TimeUnit.SECONDS)
                .build();

        OneTimeWorkRequest weatherUpdate =
            new OneTimeWorkRequest.Builder(WeatherUpdateWorker.class)
                .setConstraints(constraints)
                .setBackoffCriteria(BackoffPolicy.LINEAR, WEATHER_BACKOFF_DELAY_ONETIME,
                    TimeUnit.SECONDS)
                .build();

        WorkManager.getInstance(getApplicationContext())
            .beginUniqueWork(WEATHER_UPDATE_WORKER, ExistingWorkPolicy.REPLACE, locationUpdate)
            .then(weatherUpdate)
            .enqueue();
        mWeatherRequestedTime = System.currentTimeMillis();

        Observer<WorkInfo> weatherObserver = new Observer<WorkInfo>() {
          @Override
          public void onChanged(WorkInfo workInfo) {
            if (workInfo != null) {
              Log.d(TAG, "weatherObserver onChanged : " + workInfo.toString());
              if (workInfo.getState().isFinished()) {
                String currentWeatherJSON = workInfo.getOutputData()
                    .getString(KEY_WEATHER_JSON);
                Log.d(TAG, "outputWeather: " + currentWeatherJSON);
                Weather newCurrentWeather = new Gson()
                    .fromJson(currentWeatherJSON, Weather.class);

                // check if newCurrentWeather is actually valid
                if (newCurrentWeather != null
                    && newCurrentWeather.getTemperature() != NO_TEMPERATURE) {
                  // copy bitmap over so we don't have to regenerate it
                  if (newCurrentWeather.getIconID() == mCurrentWeather.getIconID()) {
                    newCurrentWeather
                        .setIconBitmap(mCurrentWeather.getIconBitmap(getApplicationContext()));
                  }
                  mCurrentWeather = newCurrentWeather;
                  invalidate(); // redraw to update the displayed weather
                }
              }
            }
          }
        };

        WatchFaceUtil.observeUntilFinished(WorkManager.getInstance(getApplicationContext())
            .getWorkInfoByIdLiveData(weatherUpdate.getId()), weatherObserver);
      }
    }
  }
}