Search code examples
androidandroid-jetpackandroid-workmanager

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)

Solution

  • 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.