我在Android中有一个AsyncTask,它在不同的线程上运行异步任务(我没有掌握线程的生命周期,但可以给任务提供回调)。是否有一种方法可以等待异步任务完成后再调用Asynctask的postExecute函数?
谢谢。
我在Android中有一个AsyncTask,它在不同的线程上运行异步任务(我没有掌握线程的生命周期,但可以给任务提供回调)。是否有一种方法可以等待异步任务完成后再调用Asynctask的postExecute函数?
谢谢。
我认为你在这里应该定义一个Listener
接口,将实现该监听器的对象引用传递给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
我不想实现忙等待策略。可以使用 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
}
还有任务2
public AsyncTask2(Semaphore semaphore){
this.semaphore= semaphore;
}
onPostExecute(){
//do something
semaphore.release();
}
doInBackground()
以等待其他AsyncTask完成。 - AbdelHady任务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;
}
}
Thread.sleep(time)
来实现这个目的。 - Nigam Patro