ListenableWorker 中的线程处理
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
在某些情况下,您可能需要提供自定义线程处理策略。对于
例如,您可能需要处理基于回调的异步操作。
WorkManager 通过
ListenableWorker
。
ListenableWorker
是最基本的工作器 API;
Worker
,
CoroutineWorker
和
RxWorker
都是从此类派生而来。答
ListenableWorker
只会发出信号,指示作业何时开始、停止和离开
一切都由你自己决定在主线程上调用开始工作信号
因此,请务必转到您应用的某个后台线程
手动选择。
抽象方法
ListenableWorker.startWork()
返回ListenableFuture
Result
。答
ListenableFuture
是一个轻量级接口:它是一个Future
,可提供
用于附加监听器和传播异常的功能。在
startWork
方法,您应返回 ListenableFuture
,
在操作完成后,将使用其 Result
进行设置。您可以创建
ListenableFuture
实例:
- 如果您使用的是 Guava,请使用
ListeningExecutorService
。
- 否则,请包含
councurrent-futures
,然后使用以下代码
CallbackToFutureAdapter
。
如果您希望基于异步回调执行一些工作,
执行如下操作:
Kotlin
class CallbackWorker(
context: Context,
params: WorkerParameters
) : ListenableWorker(context, params) {
override fun startWork(): ListenableFuture<Result> {
return CallbackToFutureAdapter.getFuture { completer ->
val callback = object : Callback {
var successes = 0
override fun onFailure(call: Call, e: IOException) {
completer.setException(e)
}
override fun onResponse(call: Call, response: Response) {
successes++
if (successes == 100) {
completer.set(Result.success())
}
}
}
repeat(100) {
downloadAsynchronously("https://example.com", callback)
}
callback
}
}
}
Java
public class CallbackWorker extends ListenableWorker {
public CallbackWorker(Context context, WorkerParameters params) {
super(context, params);
}
@NonNull
@Override
public ListenableFuture<Result> startWork() {
return CallbackToFutureAdapter.getFuture(completer -> {
Callback callback = new Callback() {
int successes = 0;
@Override
public void onFailure(Call call, IOException e) {
completer.setException(e);
}
@Override
public void onResponse(Call call, Response response) {
successes++;
if (successes == 100) {
completer.set(Result.success());
}
}
};
for (int i = 0; i < 100; i++) {
downloadAsynchronously("https://www.example.com", callback);
}
return callback;
});
}
}
如果您的工作
已停止?
当工作被取消时,ListenableWorker
的 ListenableFuture
始终会被取消。
预计会停止运行。使用 CallbackToFutureAdapter
时,您只需添加一个
取消监听器,如下所示:
Kotlin
class CallbackWorker(
context: Context,
params: WorkerParameters
) : ListenableWorker(context, params) {
override fun startWork(): ListenableFuture<Result> {
return CallbackToFutureAdapter.getFuture { completer ->
val callback = object : Callback {
var successes = 0
override fun onFailure(call: Call, e: IOException) {
completer.setException(e)
}
override fun onResponse(call: Call, response: Response) {
++successes
if (successes == 100) {
completer.set(Result.success())
}
}
}
completer.addCancellationListener(cancelDownloadsRunnable, executor)
repeat(100) {
downloadAsynchronously("https://example.com", callback)
}
callback
}
}
}
Java
public class CallbackWorker extends ListenableWorker {
public CallbackWorker(Context context, WorkerParameters params) {
super(context, params);
}
@NonNull
@Override
public ListenableFuture<Result> startWork() {
return CallbackToFutureAdapter.getFuture(completer -> {
Callback callback = new Callback() {
int successes = 0;
@Override
public void onFailure(Call call, IOException e) {
completer.setException(e);
}
@Override
public void onResponse(Call call, Response response) {
++successes;
if (successes == 100) {
completer.set(Result.success());
}
}
};
completer.addCancellationListener(cancelDownloadsRunnable, executor);
for (int i = 0; i < 100; ++i) {
downloadAsynchronously("https://www.example.com", callback);
}
return callback;
});
}
}
在其他进程中运行 ListenableWorker
您还可以使用 RemoteListenableWorker
(ListenableWorker
的实现)将工作器绑定到特定进程。
RemoteListenableWorker
会使用您在构建工作请求时于输入数据中提供的两个额外参数绑定到特定进程:ARGUMENT_CLASS_NAME
和 ARGUMENT_PACKAGE_NAME
。
以下示例演示了如何构建绑定到特定进程的工作请求:
Kotlin
val PACKAGE_NAME = "com.example.background.multiprocess"
val serviceName = RemoteWorkerService::class.java.name
val componentName = ComponentName(PACKAGE_NAME, serviceName)
val data: Data = Data.Builder()
.putString(ARGUMENT_PACKAGE_NAME, componentName.packageName)
.putString(ARGUMENT_CLASS_NAME, componentName.className)
.build()
return OneTimeWorkRequest.Builder(ExampleRemoteListenableWorker::class.java)
.setInputData(data)
.build()
Java
String PACKAGE_NAME = "com.example.background.multiprocess";
String serviceName = RemoteWorkerService.class.getName();
ComponentName componentName = new ComponentName(PACKAGE_NAME, serviceName);
Data data = new Data.Builder()
.putString(ARGUMENT_PACKAGE_NAME, componentName.getPackageName())
.putString(ARGUMENT_CLASS_NAME, componentName.getClassName())
.build();
return new OneTimeWorkRequest.Builder(ExampleRemoteListenableWorker.class)
.setInputData(data)
.build();
对于每个 RemoteWorkerService
,您还需要在 AndroidManifest.xml
文件中添加服务定义:
<manifest ... >
<service
android:name="androidx.work.multiprocess.RemoteWorkerService"
android:exported="false"
android:process=":worker1" />
<service
android:name=".RemoteWorkerService2"
android:exported="false"
android:process=":worker2" />
...
</manifest>
示例
本页面上的内容和代码示例受内容许可部分所述许可的限制。Java 和 OpenJDK 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-07-27。
[null,null,["最后更新时间 (UTC):2025-07-27。"],[],[],null,["# Threading in ListenableWorker\n\nIn certain situations, you may need to provide a custom threading strategy. For\nexample, you may need to handle a callback-based asynchronous operation.\nWorkManager supports this use case with\n[`ListenableWorker`](/reference/androidx/work/ListenableWorker).\n`ListenableWorker` is the most basic worker API;\n[`Worker`](/reference/androidx/work/Worker),\n[`CoroutineWorker`](/reference/kotlin/androidx/work/CoroutineWorker), and\n[`RxWorker`](/reference/androidx/work/RxWorker) all derive from this class. A\n`ListenableWorker` only signals when the work should start and stop and leaves\nthe threading entirely up to you. The start work signal is invoked on the main\nthread, so it is very important that you go to a background thread of your\nchoice manually.\n\nThe abstract method\n[`ListenableWorker.startWork()`](/reference/androidx/work/ListenableWorker#startWork())\nreturns a `ListenableFuture` of the\n[`Result`](/reference/androidx/work/ListenableWorker.Result). A\n`ListenableFuture` is a lightweight interface: it is a `Future` that provides\nfunctionality for attaching listeners and propagating exceptions. In the\n`startWork` method, you are expected to return a `ListenableFuture`, which you\nwill set with the `Result` of the operation once it's completed. You can create\n`ListenableFuture` instances in one of two ways:\n\n1. If you use Guava, use `ListeningExecutorService`.\n2. Otherwise, include [`councurrent-futures`](/jetpack/androidx/releases/concurrent#declaring_dependencies) in your gradle file and use [`CallbackToFutureAdapter`](/reference/androidx/concurrent/futures/CallbackToFutureAdapter).\n\nIf you wanted to execute some work based on an asynchronous callback, you would\ndo something like this: \n\n### Kotlin\n\n```kotlin\nclass CallbackWorker(\n context: Context,\n params: WorkerParameters\n) : ListenableWorker(context, params) {\n override fun startWork(): ListenableFuture\u003cResult\u003e {\n return CallbackToFutureAdapter.getFuture { completer -\u003e\n val callback = object : Callback {\n var successes = 0\n\n override fun onFailure(call: Call, e: IOException) {\n completer.setException(e)\n }\n\n override fun onResponse(call: Call, response: Response) {\n successes++\n if (successes == 100) {\n completer.set(Result.success())\n }\n }\n }\n\n repeat(100) {\n downloadAsynchronously(\"https://example.com\", callback)\n }\n\n callback\n }\n }\n}\n```\n\n### Java\n\n```java\npublic class CallbackWorker extends ListenableWorker {\n\n public CallbackWorker(Context context, WorkerParameters params) {\n super(context, params);\n }\n\n @NonNull\n @Override\n public ListenableFuture\u003cResult\u003e startWork() {\n return CallbackToFutureAdapter.getFuture(completer -\u003e {\n Callback callback = new Callback() {\n int successes = 0;\n\n @Override\n public void onFailure(Call call, IOException e) {\n completer.setException(e);\n }\n\n @Override\n public void onResponse(Call call, Response response) {\n successes++;\n if (successes == 100) {\n completer.set(Result.success());\n }\n }\n };\n\n for (int i = 0; i \u003c 100; i++) {\n downloadAsynchronously(\"https://www.example.com\", callback);\n }\n return callback;\n });\n }\n}\n```\n\nWhat happens if your work is\n[stopped](/topic/libraries/architecture/workmanager/how-to/managing-work#cancelling)?\nA `ListenableWorker`'s `ListenableFuture` is always cancelled when the work is\nexpected to stop. Using a `CallbackToFutureAdapter`, you simply have to add a\ncancellation listener, as follows: \n\n### Kotlin\n\n```kotlin\nclass CallbackWorker(\n context: Context,\n params: WorkerParameters\n) : ListenableWorker(context, params) {\n override fun startWork(): ListenableFuture\u003cResult\u003e {\n return CallbackToFutureAdapter.getFuture { completer -\u003e\n val callback = object : Callback {\n var successes = 0\n\n override fun onFailure(call: Call, e: IOException) {\n completer.setException(e)\n }\n\n override fun onResponse(call: Call, response: Response) {\n ++successes\n if (successes == 100) {\n completer.set(Result.success())\n }\n }\n }\n\n completer.addCancellationListener(cancelDownloadsRunnable, executor)\n\n repeat(100) {\n downloadAsynchronously(\"https://example.com\", callback)\n }\n\n callback\n }\n }\n}\n```\n\n### Java\n\n```java\npublic class CallbackWorker extends ListenableWorker {\n\n public CallbackWorker(Context context, WorkerParameters params) {\n super(context, params);\n }\n\n @NonNull\n @Override\n public ListenableFuture\u003cResult\u003e startWork() {\n return CallbackToFutureAdapter.getFuture(completer -\u003e {\n Callback callback = new Callback() {\n int successes = 0;\n\n @Override\n public void onFailure(Call call, IOException e) {\n completer.setException(e);\n }\n\n @Override\n public void onResponse(Call call, Response response) {\n ++successes;\n if (successes == 100) {\n completer.set(Result.success());\n }\n }\n };\n\n completer.addCancellationListener(cancelDownloadsRunnable, executor);\n\n for (int i = 0; i \u003c 100; ++i) {\n downloadAsynchronously(\"https://www.example.com\", callback);\n }\n return callback;\n });\n }\n}\n```\n\nRunning a ListenableWorker in a different process\n-------------------------------------------------\n\nYou can also bind a worker to a specific process by using\n[`RemoteListenableWorker`](/reference/kotlin/androidx/work/multiprocess/RemoteListenableWorker),\nan implementation of `ListenableWorker`.\n\n`RemoteListenableWorker` binds to a specific process with two extra arguments\nthat you provide as part of the input data when building the work request:\n`ARGUMENT_CLASS_NAME` and `ARGUMENT_PACKAGE_NAME`.\n\nThe following example demonstrates building a work request that is bound to a\nspecific process: \n\n### Kotlin\n\n```kotlin\nval PACKAGE_NAME = \"com.example.background.multiprocess\"\n\nval serviceName = RemoteWorkerService::class.java.name\nval componentName = ComponentName(PACKAGE_NAME, serviceName)\n\nval data: Data = Data.Builder()\n .putString(ARGUMENT_PACKAGE_NAME, componentName.packageName)\n .putString(ARGUMENT_CLASS_NAME, componentName.className)\n .build()\n\nreturn OneTimeWorkRequest.Builder(ExampleRemoteListenableWorker::class.java)\n .setInputData(data)\n .build()\n```\n\n### Java\n\n```java\nString PACKAGE_NAME = \"com.example.background.multiprocess\";\n\nString serviceName = RemoteWorkerService.class.getName();\nComponentName componentName = new ComponentName(PACKAGE_NAME, serviceName);\n\nData data = new Data.Builder()\n .putString(ARGUMENT_PACKAGE_NAME, componentName.getPackageName())\n .putString(ARGUMENT_CLASS_NAME, componentName.getClassName())\n .build();\n\nreturn new OneTimeWorkRequest.Builder(ExampleRemoteListenableWorker.class)\n .setInputData(data)\n .build();\n```\n\nFor each `RemoteWorkerService`, you also need to add a service definition in\nyour `AndroidManifest.xml` file: \n\n```xml\n\u003cmanifest ... \u003e\n \u003cservice\n android:name=\"androidx.work.multiprocess.RemoteWorkerService\"\n android:exported=\"false\"\n android:process=\":worker1\" /\u003e\n\n \u003cservice\n android:name=\".RemoteWorkerService2\"\n android:exported=\"false\"\n android:process=\":worker2\" /\u003e\n ...\n\u003c/manifest\u003e\n```\n\nSamples\n-------\n\n- [WorkManagerMultiProcessSample](https://github.com/android/architecture-components-samples/tree/main/WorkManagerMultiprocessSample)"]]