Use the ServiceManager class to make jobs management easier.
ServiceManager(this).restartServicesStopped()
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 | |
) | |
} |