工作管理器。如何取消附加工作?

时间:2018-11-27 11:38:12

标签: android android-workmanager

我正试图取消尚未开始的任务。

我的Worker类代码:

class TestWork(context: Context, workerParams: WorkerParameters) :
Worker(context, workerParams) {

override fun doWork(): Result {
    val data = inputData.getInt(KEY_OBJ, -1)
    runBlocking {
        for (i in 1..3){
            Log.d("MyTag", "testWork: $data")
            delay(1000)
        }
    }

    return Result.SUCCESS
}

override fun onStopped() {
    super.onStopped()
    Log.d("MyTag", "stopped")
}

companion object {
        const val KEY_OBJ = "key"
        val WORK_NAME = "name"
    }
}

运行3的代码示例起作用,然后取消。 但是第二项工作仍在继续。

    val data1 = Data.Builder()
        .putInt(TestWork.KEY_OBJ, 1)
        .build()

    val workRequest1 = OneTimeWorkRequest.Builder(TestWork::class.java)
        .setInputData(data1)
        .addTag("1")
        .build()

    val data2 = Data.Builder()
        .putInt(TestWork.KEY_OBJ, 2)
        .build()

    val workRequest2 = OneTimeWorkRequest.Builder(TestWork::class.java)
        .setInputData(data2)
        .addTag("2")
        .build()

    val data3 = Data.Builder()
        .putInt(TestWork.KEY_OBJ, 3)
        .build()

    val workRequest3 = OneTimeWorkRequest.Builder(TestWork::class.java)
        .setInputData(data3)
        .addTag("3")
        .build()

    WorkManager.getInstance().enqueueUniqueWork(
        TestWork.WORK_NAME,
        ExistingWorkPolicy.APPEND,
        workRequest1
    )

    WorkManager.getInstance().enqueueUniqueWork(
        TestWork.WORK_NAME,
        ExistingWorkPolicy.APPEND,
        workRequest2
    )

    WorkManager.getInstance().enqueueUniqueWork(
        TestWork.WORK_NAME,
        ExistingWorkPolicy.APPEND,
        workRequest3
    )

    WorkManager.getInstance().cancelWorkById(workRequest2.id)

如何仅取消第二项工作?当第一个执行时

2 个答案:

答案 0 :(得分:0)

您应该在onWork方法内部使用isStopped()方法调用

在Android开发者峰会上的视频中对此进行了解释。 Around minute 15 into the presentation there's a whole section on how to stop work in WorkManager that goes through these details

答案 1 :(得分:0)

如我所见,您在取消行中犯了一个错误,必须将cancelWorkById("2")替换为cancelAllWorkByTag("2"),因为您要向作品添加标签.addTag("2")

我当前正在使用WorkManager,并且试图取消带有标签的作品,并且它可以起作用。