To wait for AsyncTask to finish you can use get() method.
From documentation of get() method:
Waits if necessary for the computation to complete, and then retrieves
its result.
AsyncTask - get()
But this will make your main thread wait for the result of the AsyncTask.
Another way would be that you can show a progress dialog in the async task until it finishes. This way you can get the status calling:
task.getStatus() == Status.RUNNING
And if the status is Status.RUNNING
you will just show the progress dialog until will be finished. So, as an example:
final AsyncTask task = MyAsyncTask.getInstance();
final Thread waitingThread = new Thread(new Runnable() {
@Override
public void run() {
try {
// ...
// show progress dialog
while(task.getStatus() != Status.FINISHED) {
TimeUnit.SECONDS.sleep(1);
}
result = task.get();
// ...
// hide progress dialog
} catch (InterruptedException e) {
// TODO log
}
}
});
waitingThread.start();
The task
object is your asyncTask. You can make it Singleton and start in Activity A, and get instance of it in Activity D.
public class MyAsyncTask extends AsyncTask<Void, Void, Void>{
private static MyAsyncTask instance;
private MyAsyncTask(){}
public static MyAsyncTask getInstance() {
// check status if we want to execute it again
if (instance == null) {
instance = new MyAsyncTask();
} else if (instance.getStatus() == Status.FINISHED) {
instance = new MyAsyncTask();
}
return instance;
}
@Override
protected Void doInBackground(Void... params) {
// do smth
return null;
}
}
Haven't tried this in action but I think it will work.