user3660061
user3660061

Reputation: 69

Wait for an asynchronous task in asynctask in android

I have an AsyncTask in Android that runs an asynchronous task on a different thread (I don't have a hand on the Thread life but i can give a callback to the task). Is there a way to wait for the asynchronous task to finish to call the postExecute function of the Asynctask ?

Thanks,

Upvotes: 3

Views: 2620

Answers (3)

Alberto S.
Alberto S.

Reputation: 7649

I'd rather not to implement a busy-waiting strategy. Both AsyncTask can share a Semaphore that keeps one stopped while the other finishes

Init your semaphore

 private final Semaphore semaphore = new Semaphore(0);

Pass that object to both tasks

 public AsyncTask1(Semaphore semaphore){
     this.semaphore= semaphore;
 } 

 doInBackground(){
     //do something
     semaphore.acquire(); // <- Waiting till the other task finises
 }

And Task2

 public AsyncTask2(Semaphore semaphore){
     this.semaphore= semaphore;
 } 

 onPostExecute(){
   //do something
   semaphore.release();
}

Upvotes: 3

gladiator
gladiator

Reputation: 742

Task1

   private final Callback callback;
   public AsyncTask1(Callback callback){
       this.callback = callback;
   } 
   doInBackground(){
       //do something
       while(!callback.isFinished()){
           Thread.sleep(WAIT_TIME);
       }
   }

Task2

   private final Callback callback;
   public AsyncTask2(Callback callback){
       this.callback = callback;
   } 
   onPostExecute(){
       //do something
       callback.setFinished(true);
   }

class Callback{
    private volatile boolean finished = false;
    public void setFinished(boolean finished){
        this.finished = finished;
    }
}

Upvotes: 0

Yury Fedorov
Yury Fedorov

Reputation: 14928

I think what you should do here is define a Listener interface, pass a reference to an object implementing that listener to your AsyncTask, and call this object's method from your onPostExecute.

// this is your interface
// create it in its own file or as an inner class of your task
public interface OnTaskFinishListener {
    public void onTaskFinish();
}

// add the following code to your task's class
private OnTaskFinishListener mOnTaskFinishListener;
public void setOnTaskFinishListener(OnTaskFinishListener listener) {
    mOnTaskFinishListener = listener;
}

// in your onPostExecute method call this listener like this
// this will call the implemented method on the listener that you created
if (mOnTaskFinishListener != null) {
    mOnTaskFinishListener.onTaskFinish();
}

// suppose this is where you start your task
MyBackgroundTask task = new MyBackgroundTask();

// set new listener to your task - this listener will be called
// when onPostExecutes completed -> that's what you need
task.setOnTaskFinishListener(new OnTaskFinishListener() {
    @Override
    public void onTaskFinish() {
        // implement your code here
    }
});
task.execute(); // and start the task 

Upvotes: 2

Related Questions