Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all AsyncTasks that are executed and currently running in Android app

I have a number of AsyncTask instances that are downloading some different content from the server. They run on executor:

final GetStationsTask getStationsTask = new GetStationsTask();
getStationsTask
        .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, URL_STATIONS);

Currently I have 3 subclasses of AsyncTask, but this number will not stay the same. I am also implementing some kind of retrying for tasks that were not completed for different reasons, and I would like to download everything from the beginning, if at least one of the tasks was not finished correctly (the data was not received):

// mHandler = new Handler(); // an instance variable
mHandler.postDelayed(new Runnable() {
    @Override
    public void run() {
        if (!allDataSet()) {
            // here I want to cancel the tasks that are still running
            // and rerun all of them
        }
    }
}, 30000); // I give all the tasks 30 seconds to complete

For that I suppose I need to know which tasks are currently running, which tasks have finished correctly and which ones were cancelled, because if all the tasks get restarted, I need to cancel the running ones first to prevent the data from being received multiple times. Any ideas how to solve it?

like image 356
Yury Fedorov Avatar asked Dec 23 '15 08:12

Yury Fedorov


People also ask

How do I know if async is already running?

Use getStatus() to get the status of your AsyncTask . If status is AsyncTask. Status. RUNNING then your task is running.

How can I check if an app running on Android?

To open Quick Settings, from the top of the screen, swipe down twice. To see the number of active apps running in the background: At the bottom left, tap # active apps. Or, at the bottom right, tap the number next to Settings and Power .

What can I use instead of AsyncTask?

This class was deprecated in API level 30. Use the standard java. util. concurrent or Kotlin concurrency utilities instead.

How many threads are there in AsyncTask in Android?

In newer Android versions, 5 threads are create by default, and the ThreadPoolExecutor will attempt to run the AsyncTask s on these 5 threads. If you create more than 5 AsyncTask s, it may either queue them or create new threads (but only up to 128).


1 Answers

Override the base AsyncTask, and use that as your base class for all AsyncTasks. Have the overriden task have a static list of running, cancelled and finished tasks. Then add each task to the relevant list in the base class methods.

like image 173
yedidyak Avatar answered Sep 25 '22 16:09

yedidyak