我正在开发一个Android应用程序,需要在一个活动中一个接一个地多次调用一个asynctask函数,如下所示:
当我执行这种类型的代码时,所有任务大致并行运行,但我需要这个任务一个接一个地运行.如何在不调用onPostExecute()中的下一个任务的情况下执行此操作
一种解决方案是在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();
}
}
Run Code Online (Sandbox Code Playgroud)
现在你的代码是:
Task t=new Task();
Task t1=new Task();
Task t2=new Task();
t.setNext(t1);
t1.setNext(t2);
t.execute();
Run Code Online (Sandbox Code Playgroud)
第二种方法是创建自己的线程池,如:
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();
}
});
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
你的代码是:
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());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3971 次 |
| 最近记录: |