Run asynchronous task in sequential order in android4.0

I have completed 2 asyn tasks, I am using android4.0. where one asyntase is performed continuously, the second is performed based on the requirement (may be mulitpe time). For instance.

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, AsynTask2 fails.

If you try to execute executeOnExecutor (AsyncTask.THREAD_POOL_Executor, params), then both asyntask are executed and I get print messages from AsynTask2, but they are not ok (for example, 0 2 6 4 10 8 12 14 ....).

Is there a way to continuously execute AsynTask1 and AsynTask2 in sequential order to prevent (e.g. 0 2 4 6 8 10 12 14 ....).

Thank you and respectfully mini.

+4
source share
4 answers

Use SERIAL_EXECUTOR for Asynctask2

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

Edit: Use for Asynctask1, so the same artist is not used

  new AsynTask1().executeOnExecutor(AsyncTask.THREAD_POOL_Executor,params); 
+4
source

Try using callbacks. Define interfaces in AsyncTask classes and implement them in the main class. Use callBack on onPostExecute AsyncTask2 to start the next AsyncTask2. You guarantee the order.

  class AsyncTask2 extends AsyncTask<String, Void,Boolean<{ //Your code. doInBackground must now return a boolean. protected Void onPostExecute(final Boolean success){ myCallback listener = (myCallback) parentActivity; listener.call(); } public Interface myCallback{ void call(); } } 

And then in your main activity you implement myCallback.

[EDIT]

Here is an example of what you could do.

 Class MainActivity extends Activity implements myCallback{ //Your code public void call(){ new AsyncTask2().execute("no is even" + i); } } 
0
source
  • You should not use AsyncTask for long threads (as you implement AsyncTask1). See Documentation: http://developer.android.com/reference/android/os/AsyncTask.html . Just create a separate thread for what AsyncTask1 does.

  • Since you need serial execution for what you are doing in AsyncTask2, you can do this by creating ThreadPool of size 1.

     // Creating ThreadPool ExecutorService service = Executors.newFixedThreadPool(1); // Submitting task service.execute(task); // Shutting down the thread pool when not required. service.shutdown(); 
0
source
  int i=0; while(i<100) { new AsynTask1().execute(); if(i%2==0) { new AsynTask2().execute("no is even"+i); } i++ } 
-2
source

All Articles