Android AsyncTask example and explanation

AndroidMobile DevelopmentProgramming

Android AsyncTask going to do background operation on background thread and update on main thread. In android we cant directly touch background thread to main thread in android development. asynctask help us to make communication between background thread to main thread.

Methods of AsyncTask

  • onPreExecute() − Before doing background operation we should show something on screen like progressbar or any animation to user. we can directly comminicate background operation using on doInBackground() but for the best practice, we should call all asyncTask methods .

  • doInBackground(Params) − In this method we have to do background operation on background thread. Operations in this method should not touch on any mainthread activities or fragments.

  • onProgressUpdate(Progress…) − While doing background operation, if you want to update some information on UI, we can use this method.

  • onPostExecute(Result) − In this method we can update ui of background operation result.

Generic Types in Async Task

  • TypeOfVarArgParams − It contains information about what type of params used for execution.

  • ProgressValue − It contains information about progress units. While doing background operation we can update information on ui using onProgressUpdate().

  • ResultValue −It contains information about result type.

This example demonstrate about how to use asyncTask in android.

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = ""
   xmlns:tools = ""
   android:id = "@+id/rootview"
   android:layout_width = "match_parent"
   android:layout_height = "match_parent"
   android:orientation = "vertical"
   android:background = "#c1c1c1"
   android:gravity = "center_horizontal"
   tools:context = ".MainActivity">
   android:id = "@+id/asyncTask"
   android:text = "Download"
   android:layout_width = "wrap_content"
   android:layout_height = "wrap_content" />
   android:id = "@+id/image"
   android:layout_width = "300dp"
   android:layout_height = "300dp" />

In the above xml we have created a button, when user click on the button it going to download image and append image to imageview.

Step 3 − Add the following code to src/

package com.example.andy.myapplication;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
   URL ImageUrl = null;
   InputStream is = null;
   Bitmap bmImg = null;
   ImageView imageView= null;
   ProgressDialog p;
   protected void onCreate(Bundle savedInstanceState) {
      Button button=findViewById(;
      button.setOnClickListener(new View.OnClickListener() {
         public void onClick(View v) {
            AsyncTaskExample asyncTask=new AsyncTaskExample();
   private class AsyncTaskExample extends AsyncTask<String, String, Bitmap> {
      protected void onPreExecute() {
         p = new ProgressDialog(MainActivity.this);
         p.setMessage("Please wait...It is downloading");
      protected Bitmap doInBackground(String... strings) {
         try {
            ImageUrl = new URL(strings[0]);
            HttpURLConnection conn = (HttpURLConnection) ImageUrl.openConnection();
            is = conn.getInputStream();
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            bmImg = BitmapFactory.decodeStream(is, null, options);
         } catch (IOException e) {
         return bmImg;
      protected void onPostExecute(Bitmap bitmap) {
         if(imageView!=null) {
         }else {

In the above code we are downloading image using asyncTask and appending image to imageview.

Step 4 − Add the following code to manifest.xml

<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = ""
package = "com.example.andy.myapplication">
   <uses-permission android:name = "android.permission.INTERNET"/>
      android:allowBackup = "true"
      android:icon = "@mipmap/ic_launcher"
      android:label = "@string/app_name"
      android:roundIcon = "@mipmap/ic_launcher_round"
      android:supportsRtl = "true"
      android:theme = "@style/AppTheme">
      <activity android:name = ".MainActivity">
            <action android:name = "android.intent.action.MAIN" />
            <category android:name = "android.intent.category.LAUNCHER" />

In the above AndroidManifest.xml file we have added internet permission to access internet to download image.

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen.


Now click on download button it will show progress on UI and download image at background as shown below

Downloading In Progress

After downloading image, it will update on UI as shown below


Click here to download the project code

Published on 05-Dec-2018 17:42:17