WORK MANAGER IN Dawood Ilyas
ANDROID
WHAT IS IT?
WorkManager is an Android library that runs deferrable background work when
the work’s constraints are satisfied.
WorkManager is intended for tasks that require a guarantee that the system will run
them even if the app exits.
A BIT HISTORY ABOUT ITS
PREDECESSORS
Services
Job Schedulers
Job Dispatchers
Foreground services
Alarm Manager
WHEN TO USE IT?
UNDER THE HOOD
KEY FEATURES:
Backwards compatible up to API 14
oUses JobScheduler on devices with API 23+
oUses a combination of BroadcastReceiver + AlarmManager on devices with API 14-
22
Add work constraints like network availability or charging status
Schedule asynchronous one-off or periodic tasks
Monitor and manage scheduled tasks
Chain tasks together
Ensures task execution, even if the app or device restarts
Adheres to power-saving features like Doze mode
KEY COMPONENTS:
Worker classs
WorkRequest
OneTimeWorkRequest
PeriodicWorkRequest
WorkManager
WorkInfo
WORKER CLASS
For creating a worker we need to create a class that
is extending Worker
DEFINING Kotlin:
INPUT/OUTPUT
Input and output values are stored as key-value
pairs in a Data object.
Java:
WORK REQUEST:
ONETIMEWORKREQUEST
WORK REQUEST:
PERIODICWORKREQUEST
WORK CONSTRAINTS
WORK REQUEST
REAL POWER OF WORK
MANAGER: CHAINING
What if we wanted to filter multiple images, then compress them. and then upload
them. If you want to run a series of WorkRequests, one after the other or even in
parallel, you can use a chain.
The example diagram shows a chain where you have three filter tasks run in parallel,
followed by a compress task and an upload task, run in sequence:
CODE
Assuming you have created all your WorkRequests with the appropriate constraints, the
code looks like:
WORK INFO’S STATES
LIFE CYCLE OF WORK
TAGGING WORK
OBSERVING WORK
UNIQUE WORK
STOPPING A RUNNING TASK
REFERENCES
https://developer.android.com/topic/libraries/architecture/workmanage
https://medium.com/google-developer-experts/services-the-life-with-without-and-w
orker-6933111d62a6