ListenableWorker 中的多线程

在某些情况下,您可能需要提供自定义的线程策略。例如,您可能需要处理基于回调的异步操作。WorkManager 使用 ListenableWorker 支持此用例。ListenableWorker 是最基本的 Worker API;WorkerCoroutineWorkerRxWorker 都派生自此类。ListenableWorker 仅在工作应开始和停止时发出信号,并将线程完全留给您处理。开始工作信号在主线程上调用,因此,手动切换到您选择的后台线程非常重要。

抽象方法 ListenableWorker.startWork() 返回 ResultListenableFutureListenableFuture 是一个轻量级接口:它是一个提供附加侦听器和传播异常功能的 Future。在 startWork 方法中,您需要返回一个 ListenableFuture,操作完成后,您将使用操作的 Result 设置该 ListenableFuture。您可以通过以下两种方式之一创建 ListenableFuture 实例

  1. 如果您使用 Guava,请使用 ListeningExecutorService
  2. 否则,在您的 gradle 文件中包含 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;
        });
    }
}

如果您的工作 停止 会发生什么?当预期工作停止时,ListenableWorkerListenableFuture 始终会被取消。使用 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

您还可以通过使用 RemoteListenableWorkerListenableWorker 的实现)将 Worker 绑定到特定进程。

RemoteListenableWorker 使用构建工作请求时作为输入数据的一部分提供的两个额外参数绑定到特定进程:ARGUMENT_CLASS_NAMEARGUMENT_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>

示例