Skip to content

Instantly share code, notes, and snippets.

@robertlevonyan
Created March 6, 2019 12:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertlevonyan/4fdf42177f330a8cbb37d778d851b05a to your computer and use it in GitHub Desktop.
Save robertlevonyan/4fdf42177f330a8cbb37d778d851b05a to your computer and use it in GitHub Desktop.
fun createConstraints() = Constraints.Builder()
.setRequiredNetworkType(NetworkType.UNMETERED) // if connected to WIFI
// other values(NOT_REQUIRED, CONNECTED, NOT_ROAMING, METERED)
.setRequiresBatteryNotLow(true) // if the battery is not low
.setRequiresStorageNotLow(true) // if the storage is not low
.build()
fun createWorkRequest(data: Data) = PeriodicWorkRequestBuilder<LocationWorker>(12, TimeUnit.HOURS) // setting period to 12 hours
// set input data for the work
.setInputData(data)
.setConstraints(createConstraints())
// setting a backoff on case the work needs to retry
.setBackoffCriteria(BackoffPolicy.LINEAR, PeriodicWorkRequest.MIN_BACKOFF_MILLIS, TimeUnit.MILLISECONDS)
.build()
fun startWork() {
// set the input data, it is like a Bundle
val work = createWorkRequest(Data.EMPTY)
/* enqueue a work, ExistingPeriodicWorkPolicy.KEEP means that if this work already existits, it will be kept
if the value is ExistingPeriodicWorkPolicy.REPLACE, then the work will be replaced */
WorkManager.getInstance().enqueueUniquePeriodicWork("Smart work", ExistingPeriodicWorkPolicy.KEEP, work)
// Observe the result od the work
WorkManager.getInstance().getWorkInfoByIdLiveData(work.id)
.observe(lifecycleOwner, Observer { workInfo ->
if (workInfo != null && workInfo.state == WorkInfo.State.SUCCEEDED) {
// FINISHED SUCCESSFULLY!
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment