Android多个AsyncTasks一个接一个

时间:2014-01-19 22:30:55

标签: android android-asynctask

我正在开发一个Android应用程序,需要在一个活动中一个接一个地多次调用一个asynctask函数:

  • ..一些代码
  • new task()。execute();
  • ..其他代码
  • new task()。execute();
  • ..其他代码
  • new task()。execute();

当我执行这种类型的代码时,所有任务大致并行运行,但我需要这些任务一个接一个地运行。 如何在不调用onPostExecute()

的下一个任务的情况下执行此操作

2 个答案:

答案 0 :(得分:5)

一种解决方案是在AsyncTask类中创建一个AsyncTask对象,如:

class Task extends AsyncTask {
AsyncTask next;
public void setNext(AsyncTask next){
   this.next=next;
}

//in last line of post execute
   if(next!=null){
       next.execute();
   }
}

现在您的代码将是:

Task t=new Task();
Task t1=new Task();
Task t2=new Task();
t.setNext(t1);
t1.setNext(t2);
t.execute();

第二种方法是创建自己的线程池,如:

 class ThreadPool implements Runnable {
    ConcurrentLinkedQueue<AsyncTask> tasks = new ConcurrentLinkedQueue<AsyncTask>();
    Activity activity;

    public ThreadPool(Activity activity) {
        this.activity = activity;
    }

    boolean stop = false;

    public void stop() {
        stop = true;
    }

    public void execute(AsyncTask task) {
        tasks.add(task);
    }

    @Override
    public void run() {
        while (!stop) {
            if (tasks.size() != 0) {

                final AsyncTask task = tasks.remove();
                activity.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        task.execute();
                    }
                });

            }
        }
    }
}

您的代码将是:

ThreadPool pool=new ThreadPool(this);
pool.start();    
.. some code
pool.execute(new task());
.. other code
pool.execute(new task());
.. other code
pool.execute(new task());

答案 1 :(得分:0)

每次制作AsyncTask对象会花费更多的内存和性能,因为每次都需要创建新对象并使用它一次并创建新对象等等,有办法帮助您使用Handler安排任务和这里有关于如何实现它的示例

http://binarybuffer.com/2012/07/executing-scheduled-periodic-tasks-in-android

相关问题