[英]Wait async tasks in android
我是 android 开发的新手,我想问一下如何等待一些已经在运行的异步任务。 此外,当我试图让主线程休眠时,其中许多都被系统挂起。 当我使用 arraylist 添加它们然后调用每个 get() 时,它们中的许多永远不会按时完成。 请给我一个代码示例,因为我搜索了三天......谢谢!!
for(){
async...
async.execute();
arraylist.add(async);
}
...
for(arraylist.size){
arraylist.get().get();
}
我会在这里尝试回答您的问题,但问题不清楚。
如果你想检查是否存在AsyncTask
完成或没有一个ArrayList,我们可以使用getStatus
调用返回了我们的地位,以及状态之一,幸运的是,被FINISHED
,这样你就可以检查你的任何给定的AsyncTask的状态。
如果您想在其中一个AsyncTask
完成之前睡觉,那么最好的方法可能是在onPostExecute
做一些事情。 当你覆盖它时,你可以做一些事情来通知主线程。 您可以在此处执行此操作的方法之一:
public interface Callback {
public void callBack(int id);
}
public class MainActivity implements Callback {
private void function() {
//do your thing
AsyncTask task0 = new MyAsyncTask(this, 0); //implement your own asynctask here,
//with one of the parameters this activity so that you can get a callback.
//Also, optionally give in the id so that you know what index of asynctask is finished first.
//do the same thing for other tasks
task1.execute(params);
}
public void callBack(int id) {
arrayList.get(id).get(); //this is done
}
在您的AsyncTask
,您只需将onPostExecute
覆盖为类似的内容
protected void onPostExecute (Result result) {
//do your thing
mainActivity.callBack(id);
}
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.