WorkManager中的Worker和ListenableWorker有什么区别?

时间:2019-02-19 09:21:29

标签: java android android-workmanager

我通过此链接Migrating from Firebase JobDispatcher to WorkManager

我发现有 Worker ListenableWorker ,这两个都可以在哪里使用?使用其中任何一个有什么优势?

工人:

import android.content.Context;
import androidx.work.Data;
import androidx.work.ListenableWorker.Result;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

class MyWorker extends Worker {

  public MyWorker(@NonNull Context appContext, @NonNull WorkerParameters params) {
    super(appContext, params);
  }

  @Override
  public ListenableWorker.Result doWork() {
    // Do your work here.
    Data input = getInputData();

    // Return a ListenableWorker.Result
    Data outputData = new Data.Builder()
        .putString(“Key”, “value”)
        .build();
    return Result.success(outputData);
  }

  @Override
  public void onStopped() {
    // Cleanup because you are being stopped.
  }
}

ListenableWorker:

import android.content.Context;
import androidx.work.ListenableWorker;
import androidx.work.ListenableWorker.Result;
import androidx.work.WorkerParameters;
import com.google.common.util.concurrent.ListenableFuture;

class MyWorker extends ListenableWorker {

  public MyWorker(@NonNull Context appContext, @NonNull WorkerParameters params) {
    super(appContext, params);
  }

  @Override
  public ListenableFuture<ListenableWorker.Result> startWork() {
    // Do your work here.
    Data input = getInputData();

    // Return a ListenableFuture<>
  }

  @Override
  public void onStopped() {
    // Cleanup because you are being stopped.
  }
}

1 个答案:

答案 0 :(得分:1)

Worker在后​​台线程上同步运行。 ListenableWorker应该异步运行-在主线程上调用它们,并且应该提供所有线程(例如将它们移至后台线程)。 Worker更简单,并且有望成为您应用程序的基本构建块。您可以在这里阅读有关它们的更多信息:

https://developer.android.com/reference/androidx/work/Worker https://developer.android.com/reference/androidx/work/ListenableWorker

如果您有兴趣,也可以签出CoroutineWorkerRxWorker