我通过此链接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.
}
}
答案 0 :(得分:1)
Worker
在后台线程上同步运行。 ListenableWorker
应该异步运行-在主线程上调用它们,并且应该提供所有线程(例如将它们移至后台线程)。 Worker
更简单,并且有望成为您应用程序的基本构建块。您可以在这里阅读有关它们的更多信息:
https://developer.android.com/reference/androidx/work/Worker https://developer.android.com/reference/androidx/work/ListenableWorker
如果您有兴趣,也可以签出CoroutineWorker
和RxWorker
。