Need Context in WorkManager
Asked Answered
E

2

13

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)
Empathize answered 1/8, 2018 at 12:34 Comment(0)
C
34

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.

Ciliolate answered 1/8, 2018 at 12:39 Comment(3)
You can get context from the constructor of Worker class: developer.android.com/reference/androidx/work/…Quell
So WorkManager can run jobs even with the app killed, exactly which app's context is returned here?Amherst
When app is killed, it should not work, but when app is running and you invoke WorkManager without Activity context, but with App context (e.g. from another place of the app), it should work.Ciliolate
A
2

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.

Advertising answered 1/6, 2020 at 3:7 Comment(5)
It's the same thing actually! The context passed as an argument is what gets returned from getApplicationContext(). Refer the implementation of the Worker class!Interlope
If that's so, then what's the purpose of passing a context in through the Worker's constructor? It would seem that the purpose is for the logic in the Worker to use that context if needed?Advertising
You got that right! The worker object internally uses the context for its own purpose. There is hardly any android framework/library construct not needing the context object!Interlope
So if we're subclassing Worker, it seems reasonable to use that context object for our class too, doesn't it?Advertising
you are right @auspicious99, using getApplicationContext() in the worker class throws an exception in some cases. it is preferred to use context from the Worker's constructor.Chinoiserie

© 2022 - 2024 — McMap. All rights reserved.