androidx.work.NetworkType Java Examples

The following examples show how to use androidx.work.NetworkType. 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: MysplashMuzeiWorker.java    From Mysplash with GNU Lesser General Public License v3.0 8 votes vote down vote up
static void enqueue() {
    WorkManager.getInstance().enqueue(
            new OneTimeWorkRequest.Builder(MysplashMuzeiWorker.class).setConstraints(
                    new Constraints.Builder()
                            .setRequiredNetworkType(NetworkType.CONNECTED)
                            .build()
            ).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: WorkerHelper.java    From GeometricWeather with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void setTodayForecastUpdateWork(Context context,
                                              String todayForecastTime, boolean nextDay) {
    OneTimeWorkRequest request = new OneTimeWorkRequest.Builder(TodayForecastUpdateWorker.class)
            .setInitialDelay(
                    getForecastAlarmDelayInMinutes(todayForecastTime, nextDay),
                    TimeUnit.MINUTES
            ).setConstraints(
                    new Constraints.Builder()
                            .setRequiredNetworkType(NetworkType.CONNECTED)
                            .build()
            ).build();

    WorkManager.getInstance(context).enqueueUniqueWork(
            WORK_NAME_TODAY_FORECAST,
            ExistingWorkPolicy.REPLACE,
            request
    );
}
 
Example #5
Source File: WorkerHelper.java    From GeometricWeather with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void setTomorrowForecastUpdateWork(Context context,
                                                 String tomorrowForecastTime, boolean nextDay) {
    OneTimeWorkRequest request = new OneTimeWorkRequest.Builder(TomorrowForecastUpdateWorker.class)
            .setInitialDelay(
                    getForecastAlarmDelayInMinutes(tomorrowForecastTime, nextDay),
                    TimeUnit.MINUTES
            ).setConstraints(
                    new Constraints.Builder()
                            .setRequiredNetworkType(NetworkType.CONNECTED)
                            .build()
            ).build();

    WorkManager.getInstance(context).enqueueUniqueWork(
            WORK_NAME_TOMORROW_FORECAST,
            ExistingWorkPolicy.REPLACE,
            request
    );
}
 
Example #6
Source File: JobProxyWorkManager.java    From android-job with Apache License 2.0 6 votes vote down vote up
@NonNull
private static NetworkType mapNetworkType(@NonNull JobRequest.NetworkType networkType) {
    switch (networkType) {
        case ANY:
            return NetworkType.NOT_REQUIRED;
        case METERED:
            return NetworkType.METERED;
        case CONNECTED:
            return NetworkType.CONNECTED;
        case UNMETERED:
            return NetworkType.UNMETERED;
        case NOT_ROAMING:
            return NetworkType.NOT_ROAMING;
        default:
            throw new IllegalStateException("Not implemented");
    }
}
 
Example #7
Source File: NotiWorker.java    From hipda with GNU General Public License v2.0 6 votes vote down vote up
public static void scheduleOrCancelWork() {
    if (HiSettingsHelper.getInstance().isNotiTaskEnabled()) {
        Constraints constraints = new Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED)
                .build();

        PeriodicWorkRequest request
                = new PeriodicWorkRequest
                .Builder(NotiWorker.class, NOTI_REPEAT_MINUTTE, TimeUnit.MINUTES)
                .setConstraints(constraints)
                .build();
        WorkManager.getInstance()
                .enqueueUniquePeriodicWork(WORK_NAME, ExistingPeriodicWorkPolicy.KEEP, request);
    } else {
        WorkManager.getInstance().cancelUniqueWork(WORK_NAME);
    }
}
 
Example #8
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 #9
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 #10
Source File: CandyBarArtWorker.java    From candybar with Apache License 2.0 5 votes vote down vote up
public static void enqueueLoad(Context context) {
    WorkManager manager = WorkManager.getInstance(context);
    Constraints constraints = new Constraints.Builder()
            .setRequiredNetworkType(NetworkType.CONNECTED)
            .build();
    WorkRequest request = new OneTimeWorkRequest.Builder(CandyBarArtWorker.class)
            .setConstraints(constraints)
            .build();
    manager.enqueue(request);
}
 
Example #11
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 #12
Source File: DataSyncWorkManager.java    From ground-android with Apache License 2.0 4 votes vote down vote up
private Constraints getWorkerConstraints() {
  // TODO: Make required NetworkType configurable.
  return new Constraints.Builder().setRequiredNetworkType(NetworkType.NOT_ROAMING).build();
}
 
Example #13
Source File: ApplicationContext.java    From deltachat-android with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onCreate() {
  super.onCreate();

  // if (LeakCanary.isInAnalyzerProcess(this)) {
  //   // This process is dedicated to LeakCanary for heap analysis.
  //   // You should not init your app in this process.
  //   return;
  // }
  // LeakCanary.install(this);

  Log.i("DeltaChat", "++++++++++++++++++ ApplicationContext.onCreate() ++++++++++++++++++");

  System.loadLibrary("native-utils");
  dcContext = new ApplicationDcContext(this);

  new ForegroundDetector(ApplicationContext.getInstance(this));

  BroadcastReceiver networkStateReceiver = new NetworkStateReceiver();
  registerReceiver(networkStateReceiver, new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION));

  KeepAliveService.maybeStartSelf(this);

  initializeRandomNumberFix();
  initializeLogging();
  initializeJobManager();
  ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
  InChatSounds.getInstance(this);

  dcLocationManager = new DcLocationManager(this);
  try {
    DynamicLanguage.setContextLocale(this, DynamicLanguage.getSelectedLocale(this));
  }
  catch (Exception e) {
    e.printStackTrace();
  }

  dcContext.setStockTranslations();

  IntentFilter filter = new IntentFilter(Intent.ACTION_LOCALE_CHANGED);
  registerReceiver(new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
          dcContext.setStockTranslations();
      }
  }, filter);

  // MAYBE TODO: i think the ApplicationContext is also created
  // when the app is stated by FetchWorker timeouts.
  // in this case, the normal threads shall not be started.
  Constraints constraints = new Constraints.Builder()
          .setRequiredNetworkType(NetworkType.CONNECTED)
          .build();
  PeriodicWorkRequest fetchWorkRequest = new PeriodicWorkRequest.Builder(
          FetchWorker.class,
          PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS, // usually 15 minutes
          TimeUnit.MILLISECONDS,
          PeriodicWorkRequest.MIN_PERIODIC_FLEX_MILLIS, // the start may be preferred by up to 5 minutes, so we run every 10-15 minutes
          TimeUnit.MILLISECONDS)
          .setConstraints(constraints)
          .build();
  WorkManager.getInstance(this).enqueueUniquePeriodicWork(
          "FetchWorker",
          ExistingPeriodicWorkPolicy.KEEP,
          fetchWorkRequest);
}
 
Example #14
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);
      }
    }
  }
}