Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need Context in WorkManager

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)
like image 772
Alireza A. Ahmadi Avatar asked Aug 01 '18 12:08

Alireza A. Ahmadi


People also ask

How do I get context in WorkManager?

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.

What is the correct statement for WorkManager?

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.

What is WorkManager explain in depth?

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.

How do you pass parameters to WorkManager?

public static OneTimeWorkRequest create(String id) { Data inputData = new Data. Builder() . putString(TASK_ID, id) . build(); return new OneTimeWorkRequest.


2 Answers

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.

like image 164
Piotr Wittchen Avatar answered Oct 23 '22 06:10

Piotr Wittchen


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.

like image 42
auspicious99 Avatar answered Oct 23 '22 06:10

auspicious99