AsyncTask Android Example

October 15, 2012
By

AsyncTask is a helper abstract class used to execute short operations ( few seconds ) in a non-ui thread. In other words, AsyncTask is a helper class used to create asynchronous tasks.

An asynchronous task is defined by three generic types called Params, Progress and Result.

Params: Params is used to send arguments to an asynchronous task.

Progress: Progress is used to send data from the asynchronous task to UI thread ( Main Thread ) while task is progressing.

Result: Result is used to send data from the the asynchronous task to UI thread, after its execution.

An asynchronous task is completed in four steps as follows :

onPreExecute: A callback method executed on UI thread on starting the task.

doInBackground: A callback method executed on non UI thread, invoked after onPreExecute method if exists.

onProgressUpdate: A callback method executed on UI thread, invoked by the publishProgress() from doInBackground() method.

onPostExecute: A callback method executed on UI thread, invoked after the completion of the task.

In this article, we will create an Android application which emulates a count down timer. In this application the count down process is executing in an asynchronous task using AsyncTask helper class.

This application is developed in Eclipse (4.2.0)  with ADT plugin ( 20.0.3 ) and Android SDK ( R20.0.3 )


1. Create a new Android application project namely “AsyncTaskDemo”

Create a new Android application project namely "AsyncTaskDemo"

Figure1 : Create a new Android application project namely "AsyncTaskDemo"


2. Design application launcher icon

Design Application Launcher Icon

Figure 2 : Design Application Launcher Icon


3. Create a blank activity to define the class MainActivity

Create a blank activity

Figure 3 : Create a blank activity


4. Enter MainActivity details

Enter MainActivity Details

Figure 4 : Enter MainActivity Details


5. Delete Android Support Library from this project, if exists

By default Eclipse ( 4.2.0) adds Android Support Library to  Android application project. For this application, we don’t need to use this support library. So the library file libs/android-support-v4.jar may be removed manually via ProjectExplorer by simply right click on the file and then clicking the menu item “delete”.


6. Update the file res/values/strings.xml


<resources>

    <string name="app_name">AsyncTaskDemo</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">AsynTask Demo</string>

</resources>


7. Update the layout of the MainActivity screen in the file res/layout/activity_main.xml


<RelativeLayout 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" >

    <TextView
        android:id="@+id/tv_counter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        tools:context=".MainActivity" />
</RelativeLayout>


8. Update the class MainActivity in the file src/in/wptrafficanalyzer/asynctaskdemo/MainActivity.java


package in.wptrafficanalyzer.asynctaskdemo;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Starts the CountDownTask
        new CountDownTask().execute();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    private class CountDownTask extends AsyncTask<Void, Integer, Void>{

        // A callback method executed on UI thread on starting the task
        @Override
        protected void onPreExecute() {
            // Getting reference to the TextView tv_counter of the layout activity_main
            TextView tvCounter = (TextView) findViewById(R.id.tv_counter);
            tvCounter.setText("******** Countdown Starts ********");
        }

        // A callback method executed on non UI thread, invoked after
        // onPreExecute method if exists
        @Override
        protected Void doInBackground(Void... params) {
            for(int i=10;i>=0;i--){
                try {
                    Thread.sleep(1000);
                    publishProgress(i); // Invokes onProgressUpdate()
                } catch (InterruptedException e) {
                }
            }
            return null;
        }

        // A callback method executed on UI thread, invoked by the publishProgress()
        // from doInBackground() method
        @Override
        protected void onProgressUpdate(Integer... values) {
            // Getting reference to the TextView tv_counter of the layout activity_main
            TextView tvCounter = (TextView) findViewById(R.id.tv_counter);

            // Updating the TextView
            tvCounter.setText( Integer.toString(values[0].intValue()));
        }

        // A callback method executed on UI thread, invoked after the completion of the task
        @Override
        protected void onPostExecute(Void result) {
            // Getting reference to the TextView tv_counter of the layout activity_main
            TextView tvCounter = (TextView) findViewById(R.id.tv_counter);
            tvCounter.setText("******** DONE ********");
        }
    }
}


9. Run the application

Screenshot of the CountDownTimer after execution

Figure 5 : Screenshot of the CountDownTimer after execution


10. Download


11. Reference

http://developer.android.com/guide/index.html


How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner