You need to use ListenableWorker if you need to execute asynchronous code. There's a Threading in ListenableWorker documentation page that covers this:

If you wanted to execute some work based on an asynchronous callback, you would do something like this:

public class CallbackWorker extends ListenableWorker {

    public CallbackWorker(Context context, WorkerParameters params) {
        super(context, params);

    public ListenableFuture<Result> startWork() {
        return CallbackToFutureAdapter.getFuture(completer -> {
            Callback callback = new Callback() {
                int successes = 0;

                public void onFailure(Call call, IOException e) {

                public void onResponse(Call call, Response response) {
                    if (successes == 100) {

            for (int i = 0; i < 100; ++i) {
                downloadAsynchronously("", callback);
            return callback;

A simpler alternative, if you're using kotlin, is to use a CoroutineWorker class.
If what you need to execute is synchronous, using a Worker class is probably simpler and enough for your use case. This is documented in Threading in Worker.

  • 1
Reply Report

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions