我在 Android 中有一个 AsyncTask ,它在另一个线程上运行异步任务(我没有关注线程生活,但我可以给回调到任务)。有没有办法等待异步任务完成调用 Asynctask 的 postExecute 函数?
谢谢,
答案 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;
}
}