Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execute the async task in serial order in 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])
    }
}

In activity class

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++
        }
    }
}     

In the above case the AsynTask2 is not executed .

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

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.

like image 598
mini Avatar asked Aug 24 '12 08:08

mini


1 Answers

Use SERIAL_EXECUTOR for Asynctask2

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

Edit: Use for Asynctask1 , so that same executor is not used

 new AsynTask1().executeOnExecutor(AsyncTask.THREAD_POOL_Executor,params);
like image 170
nandeesh Avatar answered Oct 06 '22 19:10

nandeesh