Created
March 6, 2019 12:58
-
-
Save robertlevonyan/4fdf42177f330a8cbb37d778d851b05a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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