在Android4.0的串行顺序执行异步任务串行、顺序、任务

2023-09-06 03:44:42 作者:①点小任性

我已经实现了2 ASYN任务,我使用的Andr​​oid4.0。其中一个asyntask连续执行,第二个是基于要求执行的(可以是mulitpe倍)。 例如,

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 4 6 8 10 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顺序,这样的顺序(如0 2 4 6 8 10 12 14 ....)是pvented $ P $。

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