我正在开发Android应用程序,需要到的一个电话AsyncTask的函数多次陆续在一项活动是这样的:
I am developing an android app which needs to call one asynctask function multiple times one after another in one activity something like this:
..一些code 新任务()执行(); ..其他code 新任务()执行(); ..其他code 新任务()执行();当我执行这种类型的code的所有任务并行运行约,但我需要这个任务运行此起彼伏。我怎样才能做到这一点无需onPostExecute调用的下一个任务()
When I'm executing this type of code all tasks are running approximately in parallel, but I need this tasks to run one after another. How can I do this without calling next task in onPostExecute()
一个解决办法是在你的AsyncTask类一样创建一个AsyncTask的对象:
One solution would be to create an AsyncTask object in your AsyncTask class like:
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();
}
}
现在您的code将是:
now your code would be:
Task t=new Task();
Task t1=new Task();
Task t2=new Task();
t.setNext(t1);
t1.setNext(t2);
t.execute();
第二种方法是创建自己的线程池,如:
2nd way would be to create your own threadpool like:
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();
}
});
}
}
}
}
和您的code将是:
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());