Threading in Worker

When you use a Worker, WorkManager automatically calls Worker.doWork() on a background thread. The background thread comes from the Executor specified in WorkManager's Configuration. By default, WorkManager sets up an Executor for you—but you can also customize your own. For example, you can share an existing background Executor in your app, create a single-threaded Executor to make sure all your background work executes sequentially, or even specify a custom Executor. To customize the Executor, make sure you initialize WorkManager manually.

When configuring WorkManager manually, you can specify your Executor as follows:

Kotlin

WorkManager.initialize(
    context,
    Configuration.Builder()
         // Uses a fixed thread pool of size 8 threads.
        .setExecutor(Executors.newFixedThreadPool(8))
        .build())

Java

WorkManager.initialize(
    context,
    new Configuration.Builder()
        .setExecutor(Executors.newFixedThreadPool(8))
        .build());

Here is an example of a simple Worker that downloads the contents of a webpage 100 times:

Kotlin

class DownloadWorker(context: Context, params: WorkerParameters) : Worker(context, params) {

    override fun doWork(): ListenableWorker.Result {
        repeat(100) {
            try {
                downloadSynchronously("https://www.google.com")
            } catch (e: IOException) {
                return ListenableWorker.Result.failure()
            }
        }

        return ListenableWorker.Result.success()
    }
}

Java

public class DownloadWorker extends Worker {

    public DownloadWorker(Context context, WorkerParameters params) {
        super(context, params