Android background processing – AsyncTask

Developing on Android? Need to call the some services or sync with cloud servers or may be you need to do some time consuming task you need to do background processing

there are three ways to do that

AsyncTask

Service

Thread

Today we will see how AsyncTask works, AsyncTask is a wrapper around Threads. It allows to process something in background and post the results and progress on UI Thread in relatively very easy manner.

For implementing AsyncTask you need to extend

android.os.AsyncTask<Params, Progress, Result>

the three Type parameters that you can specify are

Params –  the type of the parameters sent to the task upon execution.

Progress –  the type of the progress units published during the background computation.

Result –  the type of the result of the background computation.

In AsyncTask you must implement the doInBackground (Params… params) method which needs to return the Result type parameter you have defined. You need to do or call the required background processing in this method. Other then that you can implement this following methods.

onPreExecute() – Runs on the UI thread before doInBackground. You can do any UI related update in this i. e. showing progressbar.

onProgressUpdate (Progress… values) – It runs on UI Thread when you call publishProgress (Progress… values) i. e. you can update your preogressbar for the progress being done in this method or may be adding fields to your layout.

OnCancelled() – is called after doInBackground (Params… params) when AsyncTask is cancelled by calling cancel(boolean) we should keep checking weather the task is cancelled using isCancelled() method inside doInBackground (Params… params).

onPostExecute (Result result) – It is executed after doInBackground the parameter Result is needed to be Type of Result you have set in your class header. The reault is what you have returned in doInBackground. onPostExecute runs on UI thread so you can reflect completion of your background processing according to the result you received. i.e. hiding the progressbar and showing the final outcome of processing.

Let us see an example on AsyncTask.

I assume you have already setup android and eclipse with adt and know how to create basic project. If not have a look here

First of all we will declare the AsycTask we want to use with following statement

AsyncTask<String, String, Void> myTask;

To make the UI we will create the following structure within main.xml file

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <LinearLayout
        android:id="@+id/Buttons"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="startTask"
        android:orientation="horizontal"
        android:text="@string/startTaskString" >

    <Button
        android:id="@+id/startTaskButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="startTask"
        android:text="@string/startTaskString" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="cancelTask"
        android:text="@string/cancelTaskString" />

    <ProgressBar
        android:id="@+id/progress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="invisible" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/ListParent"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id/Buttons"
        android:orientation="vertical" />

</RelativeLayout>

For representing this UI component in out Activity we will declare the following Fields

RelativeLayout mainLayout;

ProgressBar mProgressBar;

LinearLayout mListParent;

and here goes onCreate method of activity with helper method to show hide the ProgressBar

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    mProgressBar = (ProgressBar) findViewById(R.id.progress);
    mListParent = (LinearLayout) findViewById(R.id.ListParent);
}

public void showProgressBar(boolean show) {
    if (show) {
        mProgressBar.setVisibility(View.VISIBLE);
    } else {
    mProgressBar.setVisibility(View.INVISIBLE);
    }

}

and to add actions on the two buttons we hace added the tags

android:onClick="startTask"

and

android:onClick="cancelTask"

So when this buttons are clicked the methods startTask and cancelTask will be called . We need to create this methods in our activity.

startTask will create task and run it while cancelTask will cancel the task if it is running.

 

public void startTask(View v) {

    myTask = new AsyncTask() {
        String[] splittedString;

        @Override
        protected Void doInBackground(String... params) {

            splittedString = params[0].split(" ");
            for (String currentString : splittedString) {
                if(isCancelled()){
                    splittedString = null;
                    currentString = null;
                    break;
                }else{
                    publishProgress(currentString);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                    e.printStackTrace();
                    }
                }
            }
            return null;
        }

        protected void onCancelled() {

            showProgressBar(false);
        }

        @Override
        protected void onPostExecute(Void result) {

            super.onPostExecute(result);
            showProgressBar(false);
        }

        @Override
        protected void onPreExecute() {

            super.onPreExecute();
            showProgressBar(true);
        };

        @Override
        protected void onProgressUpdate(String... values) {

            super.onProgressUpdate(values);
            TextView mTextView = new TextView(AsyncTaskDemoActivity.this);
            mTextView.setText(values[0]);
            mListParent.addView(mTextView);
        }

    };

    myTask.execute(new String[] { "This is asyncTask Demo." });

}

public void cancelTask(View v) {

    myTask.cancel(true);

}

 

Here inside startTask we create new instance of AsyncTask and assign its handle to myTask while inside cancelTask we just call cancel() method of myTask.

You can download the source code of this tutorial from here and run it for your self.

When you click startTask button it will create new AsyncTask and execute it with parameter String “This is asyncTask Demo.” and split the string in background and display at particular interval demonstrating updating UI with process update. You may do any other background processing here and reflect it to UI through onProgressUpdate method.

Thats it for AsyncTask. We will discuss Background processing with Services in Android in Upcoming Posts.