I have 3 AsyncTasks
and 1 ProgressBar
. I want when any of task executes, the progress bar is visible and when all of them finish, the progress bar is invisible.
In Java, there is ExecutorService::isTerminated
to check if all runnables finished but Android doesn't have it.
Update: 3 tasks execute at the same time.
Figure.
You can return a Task or Task<T> and use that to determine if it's completed. Also you can use a CancellationToken and cooperative cancellation to cancel previous tasks. Right now async void is unawawaitable and fire-and-forgot so you won't have any idea if it's done or failed etc.
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params , Progress and Result , and 4 steps, called onPreExecute , doInBackground , onProgressUpdate and onPostExecute .
To start an AsyncTask the following snippet must be present in the MainActivity class : MyTask myTask = new MyTask(); myTask. execute(); In the above snippet we've used a sample classname that extends AsyncTask and execute method is used to start the background thread.
Nice graphic. But I am afraid there is no build in mechanism for this. You'll have to implement it by yourself. There are few solutions you could use -
Try using AsyncTask.getStatus(). This works perfectly fine. Refer below sample code.
List<AsyncTask<String, String, String>> asyncTasks = new ArrayList<AsyncTask<String, String, String>>(); AsyncTask<String, String, String> asyncTask1 = new uploadTask().execute(string); AsyncTask<String, String, String> asyncTask2 = new downloadTask().execute(string); AsyncTask<String, String, String> asyncTask3 = new createTask().execute(string); asyncTasks.add(asyncTask1); asyncTasks.add(asyncTask2); asyncTasks.add(asyncTask3);
You can later loop the AsyncTaskList and find each of the tasks' status as below.
for(int i=0;i<asyncTasks.size();i++){ AsyncTask<String, String, String> asyncTaskItem = (AsyncTask<String, String, String>)asyncTasks.get(i); // getStatus() would return PENDING,RUNNING,FINISHED statuses String status = asyncTaskItem.getStatus().toString(); //if status is FINISHED for all the 3 async tasks, hide the progressbar }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With