In Almost all android application we in some way or other we need to perform some of the operation in the background without freezing the UI or interrupting  the current or natural workflow.

Android provide a very nice way to implement this by providing Async Tasks.

AsyncTasks is an abstruct class with methods such as onPreExecute, doInBackground, onProgressUpdate and onPostExecute. In most cases we need to override only one method doInBackground(), but in cases where we need to update the UI on completion of the background activity we need to override the second method onPostExecute().

 private class DownloadImage extends AsyncTask<String, Integer, Bitmap>{
  
  protected Bitmap doInBackground(String... urls){
    ....// work to be done in background 
  }
  
  protected void onProgressUpdate(Integer... progress){
    ....// progress indicators here
  }
  
  protected void onPostExecute(Bitmap result){
    ....// work need to be done on background task completion
  }
 }

Now we are going to use this method to download an Image and use that image in the ImageView on the Android Activity Screen.

For This example we need to have an activity.xml layout which contains an ImageView with some id and rest of the coding need to be done in MainActivity.java class.

First we define the layout file: activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.test.downloadimagedemo.MainActivity"
    android:padding="0dp">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/backgroundImg"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

This is all we need to do in the layout file.

Now We have a class which extends AsyncTask like this.

class DownloadImage extends AsyncTask<String, Void, Bitmap>{

    String result = "";
    URL url = null;
    HttpURLConnection urlConnection = null;

    @Override
    protected Bitmap doInBackground(String... urls) {
        try {
            url = new URL(urls[0]);
            urlConnection = (HttpURLConnection) url.openConnection();

            urlConnection.connect();
            InputStream in = urlConnection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(in);
            return  myBitmap;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(Bitmap myBitmap) {
        super.onPostExecute(myBitmap);
        backgroundImg.setImageBitmap(myBitmap);
    }
}

And the MainActivity onCreate method code has to be like.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    backgroundImg = (ImageView) findViewById(R.id.backgroundImg);
    DownloadImage getImage = new DownloadImage();
    String imagesSrc = "http://tom-and-jerry-clip-art.clipartonline.net/_/rsrc/1348590336186/home/tom-and-jerry-67.png?height=320&width=320";
    getImage.execute(imagesSrc);

}

Final Result would be like this on actual phone or emulator:

do in background task in android

do in background task in android






Leave a Reply

Your email address will not be published. Required fields are marked *