在android4.0中按串行顺序执行异步任务 [英] execute the async task in serial order in android4.0

查看:32
本文介绍了在android4.0中按串行顺序执行异步任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现了 2 个异步任务,我使用的是 android4.0.其中一个异步任务连续执行,第二个根据需求执行(可能是多次).例如.

I have implemented the 2 asyn tasks, I am using android4.0. where one asyntask is executed continuously, second one is executed based on requirement(may be mulitpe times). For example.

class AsynTask1 exetends AsyncTask<Void, Bitmap, Void>{
    protected Void doInBackground(Void... params) {
        while(true){
            publishProgress(bmp);
        }
    }
}

class AsynTask2 extends AsyncTask<String, Void,Void>{
    protected Void doInBackground(String... params){
        System.out.println(params[0])
    }
}

活动课

class MainActivity extends Activity{
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new AsynTask1().execute();

        int i=0;
        while(i<100)
        {
            if(i%2==0)
            new AsynTask2().execute("no is even"+i);
            i++
        }
    }
}     

在上述情况下,不执行 AsynTask2.

In the above case the AsynTask2 is not executed .

如果尝试使用 executeOnExecutor(AsyncTask.THREAD_POOL_Executor,params),那么两个 asyntask 都会被执行,并且我正在从 AsynTask2 获取打印消息,但这些消息不是按顺序排列的(例如 0 2 6 4 10 8 12 14 ....).

If tried with executeOnExecutor(AsyncTask.THREAD_POOL_Executor,params), then both asyntask are executed and I am getting the print messages from the AsynTask2, but those are not in order(like 0 2 6 4 10 8 12 14 ....).

有什么方法可以连续执行 AsynTask1 和 AsynTask2 以 Sequential 顺序执行,以便阻止顺序(如 0 2 4 6 8 10 12 14 ....).

Is there any way to execute the AsynTask1 continuously and AsynTask2 in Sequential order so that the order(like 0 2 4 6 8 10 12 14....) is prevented.

谢谢&问候迷你.

Thanks & Regards mini.

推荐答案

使用 SERIAL_EXECUTOR 用于 Asynctask2

Use SERIAL_EXECUTOR for Asynctask2

 new AsynTask2().executeOnExecutor(AsyncTask.SERIAL_EXECUTOR ,"no is even"+i)

用于 Asynctask1 ,因此不使用相同的执行器

Use for Asynctask1 , so that same executor is not used

 new AsynTask1().executeOnExecutor(AsyncTask.THREAD_POOL_Executor,params);

这篇关于在android4.0中按串行顺序执行异步任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆