Alireza Ahmadi
Alireza Ahmadi

Reputation: 5338

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)

Upvotes: 13

Views: 13098

Answers (2)

auspicious99
auspicious99

Reputation: 4311

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.

Upvotes: 2

Piotr Wittchen
Piotr Wittchen

Reputation: 3922

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.

Upvotes: 34

Related Questions