在android中的asynctask中等待异步任务

时间:2015-12-23 10:49:17

标签: java android multithreading asynchronous android-asynctask

我在 Android 中有一个 AsyncTask ,它在另一个线程上运行异步任务(我没有关注线程生活,但我可以给回调到任务)。有没有办法等待异步任务完成调用 Asynctask postExecute 函数?

谢谢,

3 个答案:

答案 0 :(得分:1)

我认为你应该在这里做的是定义一个AsyncTask接口,将实现该监听器的对象的引用传递给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 调用该对象的方法。

preg_match_all

答案 1 :(得分:1)

我宁愿不实施忙碌的等待策略。两个AsyncTask都可以共享一个Semaphore来保持一个停止,而另一个完成

初始化你的信号量

 private final Semaphore semaphore = new Semaphore(0);

将该对象传递给两个任务

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

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

和Task2

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

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

答案 2 :(得分:0)

任务1

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

任务2

   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;
    }
}