在 WorkManager 中需要上下文

Need Context in WorkManager

我正在使用 WorkManager 1.0.0-alpha05 将某些任务安排到 运行 中,我的应用可能 运行ning 也可能不是。我要做的工作需要 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)

这取决于你需要什么样的Context。按照the documentation of the Worker class, you can simply call getApplicationContext()的方法直接从Workerclass得到整个应用的Context,在这个用例中应该是合理的。

documentation of the Worker class没有提到调用getApplicationContext()应该是获得Context的首选方式。另一方面,它确实明确记录了 Worker 的 public 构造函数将 Context 作为第一个参数。

public Worker (Context context, 
            WorkerParameters workerParams)

因此,如果您需要 Worker class 中的上下文,请使用其构造中的上下文。