I have embarked on my next app, a Twitch client app. This series will be all my notes and problems faced when creating this app.
This tutorial will be about how to get the WorkManager up and running. The more complicated task of making a API request periodically will be in the next tutorial.
When dealing with the background work, we first have to ask ourselves. What sort of work are we doing? We have 3 possible options
1) Immediate :
Tasks that must begin immediately and complete soon. May be expedited
2) Long Running :
Tasks which might run for longer, potentially longer than 10 minutes.
3) Deferrable :
Scheduled tasks that start at a later time and can run periodically. (What we are talking about)
If you are unsure about what type of work your application uses, please check out the
Documentation
If your work requires the WorkManager, using it can be broken down into a 3 step process:
1) Define the work:
2) Create a WorkRequest :
3) Submit the WorkRequest:
Work is defined using the
Worker
class. The doWork() method runs asynchronously on a background thread provided by WorkManager.
So all we have to do is to define a new class, implement the abstract Worker class and override the
doWork()
method. Just like this:
workerParams: WorkerParameters,
):Worker(appContext,workerParams){
override fun doWork(): Result {
Log.d("OAuthTokeValidationWorker","IT IS RUNNING")
return Result.success()
Once your work is defined, it must be scheduled with the WorkManager service in order to run.
For simplicities sake, we are only going to schedule this code to run once. The more complicated once per hour call will be in the next tutorial. So, creating the WorkRequest will look like this:
init{
val workManager = WorkManager.getInstance(context)
val workRequest = OneTimeWorkRequestBuilder<OAuthTokeValidationWorker>().build()
workManager.enqueue(workRequest)
Quick example of creating a custom Kotlin coroutine and scoping it to a Android service.
#
android
#
kotlin
#
mobile
#
tristan
Deleting Android database from the command line
#
android
#
mobile
#
computerscience
#
tristan
My notes on the OpenGL ES hello world triangle
#
android
#
cpp
#
mobile
Built on
Forem
— the
open source
software that powers
DEV
and other inclusive communities.
Made with love and
Ruby on Rails
. DEV Community
©
2016 - 2024.