Saturday, April 26, 2014

Run multi AsyncTask at the same time

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.

If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR.

~ reference: AsyncTask | Android Developers



This example show how to execute multi AsyncTask at the same in parallel, by calling executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) for (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB), in our StartAsyncTaskInParallel() method. The first three ProgressBars updated by AsyncTask execute in normal approach by calling execute(), the last two ProgressBar updated by AsyncTask execute in parallel.


MainActivity.java
package com.example.androidparallelasynctask;

import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;

public class MainActivity extends Activity {

 public class MyAsyncTask extends AsyncTask<Void, Integer, Void> {

  ProgressBar myProgressBar;
  
  public MyAsyncTask(ProgressBar target) {
   myProgressBar = target;
  }

  @Override
  protected Void doInBackground(Void... params) {
   for(int i=0; i<100; i++){
    publishProgress(i);
    SystemClock.sleep(100);
   }
   return null;
  }

  @Override
  protected void onProgressUpdate(Integer... values) {
   myProgressBar.setProgress(values[0]);
  }

 }
 
 Button buttonStart;
 ProgressBar progressBar1, progressBar2, progressBar3, progressBar4, progressBar5;
 MyAsyncTask asyncTask1, asyncTask2, asyncTask3, asyncTask4, asyncTask5;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  progressBar1 = (ProgressBar)findViewById(R.id.progressbar1);
  progressBar2 = (ProgressBar)findViewById(R.id.progressbar2);
  progressBar3 = (ProgressBar)findViewById(R.id.progressbar3);
  progressBar4 = (ProgressBar)findViewById(R.id.progressbar4);
  progressBar5 = (ProgressBar)findViewById(R.id.progressbar5);
  
  buttonStart = (Button)findViewById(R.id.start);
  buttonStart.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View v) {
    asyncTask1 = new MyAsyncTask(progressBar1);
    asyncTask1.execute();
    asyncTask2 = new MyAsyncTask(progressBar2);
    asyncTask2.execute();
    asyncTask3 = new MyAsyncTask(progressBar3);
    asyncTask3.execute();
    asyncTask4 = new MyAsyncTask(progressBar4);
    StartAsyncTaskInParallel(asyncTask4);
    asyncTask5 = new MyAsyncTask(progressBar5);
    StartAsyncTaskInParallel(asyncTask5);
   }});

 }
 
 @TargetApi(Build.VERSION_CODES.HONEYCOMB)
 private void StartAsyncTaskInParallel(MyAsyncTask task) {
     if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
         task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
     else
         task.execute();
 }

}

activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.example.androidparallelasynctask.MainActivity" >
    
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />
    
    <Button
        android:id="@+id/start"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Start"/>
    
    <ProgressBar
        android:id="@+id/progressbar1"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:max="100"
        android:progress="0" />
    <ProgressBar
        android:id="@+id/progressbar2"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:max="100"
        android:progress="0" />
    <ProgressBar
        android:id="@+id/progressbar3"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:max="100"
        android:progress="0" />
    <ProgressBar
        android:id="@+id/progressbar4"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:max="100"
        android:progress="0" />
    <ProgressBar
        android:id="@+id/progressbar5"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:max="100"
        android:progress="0" />
        
</LinearLayout>

This video show how it run on devices running various Android version, include:
- Nexus 7 (1st generation), Android 4.4.2
- HTC One X, Android 4.2.2
- HTC Flyer, Android 3.2.1
- Nexus One, Android 2.3.6


download filesDownload the files.

2 comments:

  1. post was really informative on Android Asynctask
    Thank you...

    ReplyDelete
  2. You are the best dude.. It seems easy to imolement..

    ReplyDelete