【问题标题】:Wait async tasks in android在android中等待异步任务
【发布时间】:2016-07-24 19:00:29
【问题描述】:

我是 android 开发的新手,我想问一下如何等待一些已经运行的异步任务。另外,当我试图睡觉时,主线程中的许多线程都被系统挂起。当我使用 arraylist 添加它们然后调用它们中的每一个 get() 时,它们中的许多永远不会按时完成。请给我一个代码示例,因为我搜索了三天... 谢谢!!

for(){
  async...
  async.execute();
  arraylist.add(async);
}
...
for(arraylist.size){
    arraylist.get().get();
}

【问题讨论】:

  • 你的意思是AsyncTask,对吧?名字很重要。 AsyncTask 用在 UI 线程上,我想在这个例子中看到更多的 UI 代码。实际编译的东西最好。
  • 你想做什么?问题不清楚。
  • AsyncTask 通过触发onPostExecute() 事件来告诉您它何时完成。供您参考:developer.android.com/intl/es/reference/android/os/…

标签: java android android-asynctask wait multitasking


【解决方案1】:

我会在这里尝试回答你的问题,但问题不清楚。

如果你想检查一个数组列表中是否有一个AsyncTask完成,我们可以使用getStatuscall返回一个status,幸运的是,其中一个状态是@987654326 @,因此您可以检查任何给定 AsyncTask 的状态。

如果您想在AsyncTask 之一完成之前睡觉,那么最好的方法可能是在onPostExecute 中做一些事情。当你override it时,你可以做一些事情来通知主线程。您可以通过以下方式执行此操作:

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

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2014-09-06
    • 1970-01-01
    • 1970-01-01
    • 2014-03-18
    • 2013-05-26
    • 2013-02-10
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多