Skip to content

Instantly share code, notes, and snippets.

@remylavergne
Created March 18, 2020 15:15
Show Gist options
  • Save remylavergne/5e50c76319d0facd8415452c1363a825 to your computer and use it in GitHub Desktop.
Save remylavergne/5e50c76319d0facd8415452c1363a825 to your computer and use it in GitHub Desktop.
[Android] WorkManager snippets
class ServiceManager(private val context: Context) {
private val globalsConstraints =
Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()
// Add new jobs here
private val allServicesAvailables =
listOf(
Service(IncidentsSynchronizationWorker::class.java, IncidentsSynchronizationWorker.TAG),
Service(AttachmentsCleaningWorker::class.java, AttachmentsCleaningWorker.TAG)
)
fun restartServicesStopped() {
val servicesNotRunning = checkAllServices()
restartServices(servicesNotRunning)
}
private fun checkAllServices(): MutableList<Service> {
val instance = WorkManager.getInstance(context)
val servicesNotRunning = mutableListOf<Service>()
allServicesAvailables.forEach { service: Service ->
val statuses = instance.getWorkInfosByTag(service.tag)
val running = try {
var running = false
val workInfoList = statuses.get()
for (workInfo in workInfoList) {
val state = workInfo.state
running =
(state == WorkInfo.State.RUNNING) or (state == WorkInfo.State.ENQUEUED)
}
running
} catch (e: ExecutionException) {
e.printStackTrace()
} catch (e: InterruptedException) {
e.printStackTrace()
}
// Store not running services
if (!running) {
servicesNotRunning.add(service)
}
}
return servicesNotRunning
}
private fun restartServices(servicesNotRunning: MutableList<Service>) {
servicesNotRunning.forEach { service: Service ->
val worker = PeriodicWorkRequest.Builder(
service.classType,
15, // TODO: Increase interval to an higher value => make custom config in each Worker :) ?
TimeUnit.MINUTES
)
.addTag(service.tag)
.setConstraints(globalsConstraints).build()
// Start
WorkManager.getInstance(context).enqueue(worker)
}
}
data class Service(
val classType: Class<out ListenableWorker>,
val tag: String
)
}

Android WorkManager Snippets

Start and restart jobs

Use the ServiceManager class to make jobs management easier.

ServiceManager(this).restartServicesStopped()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment