Home > DeveloperSection > Beginner > Thread in Android

Thread in Android


Android Android 
Ratings:
0 Comment(s)
 7096  View(s)
Rate this:

Thread in Android

Android supports standard Java Threads . You can use standard Threads and the tools from the package java.util.concurrent to put actions into the background. 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 use of Thread in an Android application. In this example I will download an image from the Internet in a thread and display a dialog until the download is done.

·         Start a new project named ThreadDemo and activity 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 and add the following permission:

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

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

Thread in Android


Don't want to miss updates? Please click the below button!

Follow MindStick