Reputation: 15752
I have an android function that calls multiple async requests. I want to know when all have finished. I saw onPostExecute() but that only tells me if one has finished. Is there a way to do this?
Upvotes: 1
Views: 206
Reputation: 1333
That tasks will take longer since AsyncTask only execute each task 1 at a time compare to a handler, and still #Mike's answer will still be applicable if you use a handler.
Upvotes: 0
Reputation: 39201
Perhaps the simplest way is to create a counter variable, e.g. int taskCount
, and set it to the number of AsyncTask
s you need to run before executing. Then create a method that will decrement the counter, and call it from the onPostExecute()
method of each task. When taskCount == 0
, the tasks will have completed.
A very simple example:
int taskCount;
private void startTasks()
{
Task task1 = new Task();
Task task2 = new Task();
Task task3 = new Task();
taskCount = 3;
task1.execute();
task2.execute();
task3.execute();
}
private void taskDone()
{
taskCount--;
if (taskCount == 0)
{
Toast.makeText(MainActivity.this, "All done!", 0).show();
}
}
private class Task extends AsyncTask <Void, Void, Void>
{
@Override
protected Void doInBackground(Void... args)
{
return null;
}
@Override
protected void onPostExecute(Void result)
{
taskDone();
}
}
Upvotes: 2