---
title: "Thread in Android(MultiThreading in android with example)"  
description: "Android supports standard Java Threads. You can use standard Threads and the tools from the package java.util.concurrent to put actions into the bac"  
author: "Chris Anderson"  
published: 2011-11-02  
updated: 2020-03-04  
canonical: https://www.mindstick.com/articles/801/thread-in-android-multithreading-in-android-with-example  
category: "android"  
tags: ["android"]  
reading_time: 8 minutes  

---

# Thread in Android(MultiThreading in android with example)

Android [supports](https://www.mindstick.com/blog/12043/how-to-create-a-killer-mobile-app-that-supports-your-brand) [standard](https://www.mindstick.com/articles/23223/naming-convention-or-coding-standard) Java Threads. You can use standard Threads and the tools from the package java.util.concurrent to put actions into the [background](https://www.mindstick.com/articles/65/how-to-change-background-color-of-tab-control-in-c-sharp). The only limitation is that you cannot directly update the UI from the background process.\

If you need to update the UI from a background task you need to use some Android-specific classes. You can use the class android.os.Handler for this or the class AsyncTasks.

In this article, I am going to explain the use of Thread in an [Android application](https://www.mindstick.com/articles/1653/creating-libraries-for-android-applications). In this example, I will [download](https://www.mindstick.com/blog/114673/download-hungry-shark-evolution-mod-apk-unlimited-money) an image from the [Internet](https://yourviews.mindstick.com/view/81617/now-it-is-time-to-say-goodbye-to-internet-explorer) in a thread and display a dialog until the download is done.

- Start a new project named ThreadDemo and [activity](https://www.mindstick.com/forum/23119/how-to-save-activity-state-in-android) ThreadActivity.
- Open **res/values/strings.xml** and add the following strings element in the resource tag:

```
<string name="downloadPicture">downloadPicture</string>
<string name="resetPicture">resetPicture</string>
```

Open **[AndroidManifest.xml](https://www.mindstick.com/interview/12768/what-is-the-androidmanifest-xml)** and add the following [permission](https://answers.mindstick.com/qa/33390/how-to-enable-api-access-in-salesforce-by-permission-set):

```
<u<uses-permission android:name="android.permission.INTERNET"></uses-permission>
```

Now set the layout of an application in the **res/layout/main.xml** file:

```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <LinearLayout android:layout_height="wrap_content"
                      android:layout_width="match_parent"
                      android:id="@+id/linearLayout1">
              <Button android:onClick="downloadPicture"
                      android:layout_height="wrap_content"
              android:text="Click to start download"

                       android:layout_width="wrap_content" />
              <Button android:onClick="resetPicture"
                        android:layout_height="wrap_content"
                        android:text="Reset Picture"
                        android:layout_width="wrap_content" />
        </LinearLayout>
        <ImageView android:src="@drawable/icon"
                    android:id="@+id/imageView1"
                    android:layout_height="match_parent"
                    android:layout_width="match_parent" />
</LinearLayout>
```

Open the Activity file and insert the following code:

```
import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;

public class ThreadActivity extends Activity {

        private static ProgressDialog dialog;
        private static ImageView imageView;
        private static Bitmap downloadBitmap;
        private static Handler handler;
        private Thread downloadThread;

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

               // Create a handler to update the UI
               handler = new Handler();

               // get the latest imageView after restart of the application
               imageView = (ImageView) findViewById(R.id.imageView1);

               // Did we already download the image?
               if (downloadBitmap != null)
                      imageView.setImageBitmap(downloadBitmap);

               // Check if the thread is already running
               downloadThread = (Thread) getLastNonConfigurationInstance();
               if (downloadThread != null && downloadThread.isAlive())
                      dialog = ProgressDialog.show(this, "Download", "downloading");
       }

        public void resetPicture(View view)
       {
               if (downloadBitmap != null)
                      downloadBitmap = null;
               imageView.setImageResource(R.drawable.icon);
       }

        public void downloadPicture(View view)
       {
               dialog = ProgressDialog.show(this, "Download", "downloading");
               downloadThread = new MyThread();
               downloadThread.start();
       }

        // Save the thread
        @Override
        public Object onRetainNonConfigurationInstance() {
               return downloadThread;
       }

        // dismiss dialog if activity is destroyed
        @Override
        protected void onDestroy() {
               if (dialog != null && dialog.isShowing())
              {
                      dialog.dismiss();
                      dialog = null;
              }
               super.onDestroy();
       }

        // Utiliy method to download image from the internet
        static private Bitmap downloadBitmap(String url) throws IOException
       {
              HttpUriRequest request = new HttpGet(url.toString());
              HttpClient httpClient = new DefaultHttpClient();
              HttpResponse response = httpClient.execute(request);

              StatusLine statusLine = response.getStatusLine();
               int statusCode = statusLine.getStatusCode();
               if (statusCode == 200)
              {
                     HttpEntity entity = response.getEntity();
                      byte[] bytes = EntityUtils.toByteArray(entity);
                     Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,
                                  bytes.length);
                      return bitmap;
              }
               else
              {
                      throw new IOException("Download failed, HTTP response code "
                           + statusCode + " - " + statusLine.getReasonPhrase());
              }
       }

        static public class MyThread extends Thread {
               @Override
               public void run() {
                      try
                     {
                            try
                           {
                                   new Thread();
                                  Thread.sleep(5000);
                           }
                            catch (InterruptedException e)
                           {
                                  e.printStackTrace();
                           }
                          downloadBitmap =downloadBitmap( downloadBitmap("http://www.mindstick.com/UserPics/156.png");
                            handler.post(new MyRunnable());
                     }
                      catch (IOException e)
                     {
                           e.printStackTrace();
                     }
              }
       }

        static public class MyRunnable implements Runnable
       {
               public void run()
              {
                      imageView.setImageBitmap(downloadBitmap);
                      dialog.dismiss();
              }
       }
}
```

· Run the application.

The output will looks like below:

![Thread in Android](https://www.mindstick.com/mindstickarticle/7a9205de-bae7-48ba-81b5-2b2ec161d672/images/e1831d59-002b-4b03-be50-b124b93e0128.png)

When you click on the button “**Click to start download**”, a downloading will start as shown below:

![Thread in Android](https://www.mindstick.com/mindstickarticle/7a9205de-bae7-48ba-81b5-2b2ec161d672/images/b7a96003-36b7-4f34-a9f0-543fbfef27c3.png)

---

Original Source: https://www.mindstick.com/articles/801/thread-in-android-multithreading-in-android-with-example

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
