articles

Home / DeveloperSection / Articles / AsyncTask in Android

AsyncTask in Android

Manoj Pandey 5139 21-Feb-2015

Previously, we learn Transmitting Network Data Using Volley in Android. Now we see how to use AsyncTask  in Android.

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.

This article describes the usage of Asynctask in your application. It also covers how to handle the application lifecycle together with threads.

What is AsyncTask?

AsyncTask is an abstract Android class which helps the Android applications to handle the Main UI thread in efficient way. Asynctask class allows us to perform long lasting tasks/background operations and show the result on the UI thread without affecting the main thread.

When to use AsyncTask?

Assume you have created a simple Android application which fetch lot of data from database then you have need to use AsyncTask.

When an asynchronous task is executed from UI main thread, the task goes through 4 steps:

onPreExecute:

Invoked before the task is executed ideally before doInBackground method is called on the UI thread. This method is normally used to setup the task like showing progress bar in the UI.

doInBackground:

Code running for long lasting time should be put in doInBackground method. When execute method is called in UI main thread, this method is called with the parameters passed.

onProgressUpdate:

Invoked by calling publish Progress at any time from doInBackground. This method can be used to display any form of progress in the user interface.

onPostExecute:

Invoked after background computation in doInBackground method completes processing. Result of the doInBackground is passed to this method.

Here I am creating an Android sample which help to clear concepts if Asynctask in Android.

1.      Create an Android project

2.      My activity_main.xml code

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical" >

 

    <Button

        android:id="@+id/Mybtn"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="Load Data" >

    </Button>

 

    <WebView

        android:id="@+id/webView"

        android:layout_width="fill_parent"

        android:layout_height="fill_parent" />

 

</LinearLayout> 

 

 3.      Add following code in MainActivity.class

package com.example.androidAsyncTask

import android.app.Activity;

import android.app.ProgressDialog;

import android.content.Context;

import android.os.AsyncTask;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.webkit.WebView;

import android.widget.Button;

 

public class MainActivity extends Activity {

            final Context context = this;

 

            /** Called when the activity is first created. */

            private ProgressDialog pDialog;

            Button myButton;

 

            @Override

            public void onCreate(Bundle savedInstanceState) {

 

                        super.onCreate(savedInstanceState);

                        setContentView(R.layout.main);

                        myButton = (Button) findViewById(R.id.Mybtn);

 

                        pDialog = new ProgressDialog(this);

                        pDialog.setMessage("Loading data Please Wait....");

                        pDialog.setCancelable(false);

                        myButton.setOnClickListener(new OnClickListener() {

 

                                    @Override

                                    public void onClick(View v) {

                                                // TODO Auto-generated method stub

                                                // Call Asyntask class

                                                LoadWebPageASYNC task = new LoadWebPageASYNC();

                                                task.execute(new String[] { "http://www.mindstick.com" });

 

                                    }

                        });

 

            }

 

            private class LoadWebPageASYNC extends AsyncTask<String, Void, String> {

                        @Override

                        protected void onPreExecute() {

                                    // Write your code which run first

                                    pDialog.show();

 

                        }

 

                        @Override

                        protected String doInBackground(String... urls) {

                                    // write your code which you perform task in background

 

                                    // WebViewis a view that displays web pages

                                    WebView webView = (WebView) findViewById(R.id.webView);

 

                                    // load url

                                    webView.loadUrl(urls[0]);

                                    // perform task which take time to complete. Here I am using for

                                    // loop

                                    for (int i = 0; i < 199999999; i++) {

                                                int a = 9;

                                                int b = 8;

                                                a = b;

                                                b = a;

 

                                    }

 

                                    return "";

                        }

 

                        @Override

                        protected void onPostExecute(String result) {

                                    // write your code which you perform task in after doInBackground()

                                    pDialog.dismiss();

                        }

            }

 

}

 Run your application

AsyncTask in Android      AsyncTask in Android


Updated 07-Sep-2019

Leave Comment

Comments

Liked By