在WorkManager中需要上下文

问题描述 投票:2回答:1

我正在使用WorkManager 1.0.0-alpha05安排一些任务在我的应用程序可能运行或未运行的功能中运行。我要做的工作需要context所以如何将上下文传递给它?

class CompressWorker : Worker() {

    override fun doWork(): Result {
        //need context here
        Log.e("alz", "work manager runs")
        return Result.SUCCESS
    }
 }

这是我如何初始化工作。

val oneTimeWork = OneTimeWorkRequestBuilder<CompressWorker>()
        .setInitialDelay(15, TimeUnit.MINUTES)
        .build()

WorkManager.getInstance().enqueue(oneTimeWork)
android android-jetpack android-workmanager
1个回答
12
投票

这取决于你需要什么样的Context。根据the documentation of the Worker class,您可以直接从getApplicationContext()类调用Worker方法来获取整个应用程序的Context,这在这个用例中应该是合理的。

© www.soinside.com 2019 - 2024. All rights reserved.