AsyncTask in Android

In Android, Services are used to keep running the application in background..If You want to small task in background then what you will do ??. In that case you have to use AsyncTask.
                     If your appication requires connection with server,loading and uploading data to server etc. In such cases,your appication becomes more complex.You can solve this by using AsyncTask.You can show a user some kind of notification or progressdialog box to display something on main screen while loading data from server in background without interuppting the main thread.

                       AsyncTask is an abstract class that provides several methods managing the interaction between the UI thread and the background thread. it’s implementation is by creating a sub class that extends AsyncTask and implementing the different protected methods it provides.

We are now going to create AsyncTasj sub class by like this:

class ServerTask extends AsyncTask<Params,Progress,Result>

It contains three parameter:
  1. Params: parameter info passed to be used by the AsyncTask.
  2. Progress: the type of progress that the task accomplishes.
  3. The result returned after the AsyncTask finishes.
Next step is we have to override the protected methods of AsyncTask class that defined its LifeCycle.

  1. onPreExecute: the first method called in the AsyncTask, called on the UI thread.
  2. doInBackground: the method that executes the time consuming tasks and publish the task progress, executed in background thread.
  3. onProgressUpdate: method that updates the progress of the AsyncTask, run on the UI thread.
  4. onPostExecute: the final method that gets called after doInBackground finishes, here we can update the UI with the results of the AsyncTask.
  5. onCancelled: gets called if the AsyncTask.cancel() methods is called, terminating the execution of the AsyncTask.

     public class Details extends Activity {
        public void onCreate(Bundle savedInstanceState) {
            ctx =this;
        private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
            protected String doInBackground(String... urls) {
                for (String url : urls) {
            //    do background task

                return String();
            protected void onPreExecute() {
                 ploading =,"" ,"");

            protected void onPostExecute(String result) {
                //set the loaded data in your ui

        public void readWebpage() {
            DownloadWebPageTask task = new DownloadWebPageTask();
            task.execute(new String[] { "http://""});





    Popular Posts