I'm using WorkManager 1.0.0-alpha05
to schedule some task to run in the feature that my app may or may not be running. The job I'm going to do requires context
so how can I pass context to this?
class CompressWorker : Worker() {
override fun doWork(): Result {
//need context here
Log.e("alz", "work manager runs")
return Result.SUCCESS
}
}
And here is how I initialized the work.
val oneTimeWork = OneTimeWorkRequestBuilder<CompressWorker>()
.setInitialDelay(15, TimeUnit.MINUTES)
.build()
WorkManager.getInstance().enqueue(oneTimeWork)
According to the documentation of the Worker class, you can simply call getApplicationContext() method directly from the Worker class to get the Context of the entire application, which should be reasonable in this use case.
WorkManager is the recommended library for persistent work. Scheduled work is guaranteed to execute sometime after its Constraints are met. WorkManager allows observation of work status and the ability to create complex chains of work.
Android WorkManager is a background processing library which is used to execute background tasks which should run in a guaranteed way but not necessarily immediately. With WorkManager we can enqueue our background processing even when the app is not running and the device is rebooted for some reason.
public static OneTimeWorkRequest create(String id) { Data inputData = new Data. Builder() . putString(TASK_ID, id) . build(); return new OneTimeWorkRequest.
It depends on what kind of Context
do you need. According to the documentation of the Worker
class, you can simply call getApplicationContext()
method directly from the Worker
class to get the Context
of the entire application, which should be reasonable in this use case.
The documentation of the Worker class does not mention that calling getApplicationContext()
should be the preferred way of getting the Context
. On the other hand, it does explicitly document that the public constructor of Worker
takes a Context
as the first parameter.
public Worker (Context context,
WorkerParameters workerParams)
So if you need a context in the Worker
class, use the one from its construction.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With