Post Top Ad

Post Top Ad

Saturday 29 April 2017

# AsyncTask in Android.


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 downloads Images file from Internet on launching the application.

How to implement AsyncTask in Android applications?

  1. Create a new class inside Activity class and subclass it by extending AsyncTask as shown below
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    private classMyTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
          //Yet to code
         }
     protected void onProgressUpdate(Integer... progress) {
         //Yet to code
         }
     protected void onPostExecute(Long result) {
         //Yet to code
         }
    }
  2. Execute the task simply by invoking execute method as shown below:

    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 publishProgress at anytime 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. 
    Task Cancellation
     The task can be cancelled by invoking cancel(boolean) method. This will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object) method is called instead of onPostExecute() after doInBackground() returns. 
    AsyncTask – Rules to be followed 
    • The AsyncTask class must be loaded on the UI thread.
    •  The task instance must be created on the UI thread
    •  Method execute(Params…) must be invoked on the UI thread. 
    •  Should not call onPreExecute(), onPostExecute(Result), doInBackground(Params…), onProgressUpdate(Progress…) manually. 
    •  The task can be executed only once (an exception will be thrown if a second execution is attempted.)




    Create New Projects Name AsyncTask
    AsyncTask\app\src\main\res\layout

    1.activity_main.xml
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout 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:orientation="vertical">


        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/download_img"
            android:layout_gravity="center_vertical" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/download_next"
            android:layout_gravity="right" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/download_nextimg"
            android:layout_gravity="center_horizontal" />
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/download_nexttimeimg"
            android:layout_gravity="center_horizontal" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Download"
            android:id="@+id/button"
            android:onClick="downloadImage" />

    </LinearLayout>

    2.AsyncTask\app\src\main\java\com\problemhunt\tanuj\asynctask:
    MainActivity.java

    package com.problemhunt.tanuj.asynctask;

    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    import android.widget.ImageView;

    public class MainActivity extends AppCompatActivity {

        private ImageView mDownloadImgV;
        private ImageView mDownloadNext;
        private ImageView mDownloadImgNext;
        private ImageView mDownloadNextTimeImg;


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            mDownloadImgV=(ImageView) findViewById(R.id.download_img);
            mDownloadNext=(ImageView) findViewById(R.id.download_next);
            mDownloadImgNext=(ImageView)  findViewById(R.id.download_nextimg);
            mDownloadNextTimeImg=(ImageView) findViewById(R.id.download_nexttimeimg);
        }

        public void downloadImage(View view) {
            MyTask myTask=new MyTask(mDownloadImgV,mDownloadNext,mDownloadImgNext,mDownloadNextTimeImg,MainActivity.this);
            myTask.execute("http://images.indianexpress.com/2015/07/kalam_pranab_759.jpg","http://images.indianexpress.com/2015/07/kalam_dd_759.jpg","http://cdn.narendramodi.in/cmsuploads/0.34592100-1450848819-indian-pm-narendra-modi-russia-remains-our-principal-partner.jpg","http://astrotarot.net/wp-content/uploads/2015/09/army.jpg");
               }


        }


    Create Class MyTask.java

     package com.smartpropertyhunt.tanuj.asynctask;

    import android.app.ProgressDialog;
    import android.content.Context;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.os.AsyncTask;
    import android.util.Log;
    import android.widget.ImageView;

    import java.io.BufferedInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URL;
    import java.net.URLConnection;
    import java.util.ArrayList;

    /**
     * Created by Tanuj on 06/09/2016.
     */
    public class MyTask extends AsyncTask<String,String,ArrayList<Bitmap>> {
        ImageView mImageView;
        ImageView  vImageView;
        ImageView nImageView;
        ImageView iImageView;
        private Context mContext;
        private ProgressDialog mprogressDialog;
        ArrayList<Bitmap> marry= new ArrayList<Bitmap>();


        public MyTask(ImageView mImageView,ImageView  vImageView,  ImageView nImageView,ImageView iImageView,Context mContext) {
            this.mImageView = mImageView;
            this.vImageView=vImageView;
            this.nImageView=nImageView;
            this.iImageView=iImageView;
            this.mContext = mContext;
            mprogressDialog = new ProgressDialog(mContext);

        }

        @Override
        protected ArrayList<Bitmap> doInBackground(String... params) {

            Bitmap bm = null;
            for (int i=0;i<=3;i++)
            {
                try {
                    URL aURL = new URL(params[i]);
                    URLConnection conn = aURL.openConnection();
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    BufferedInputStream bis = new BufferedInputStream(is);
                    bm = BitmapFactory.decodeStream(bis);
                    marry.add(bm);
                    bis.close();
                    is.close();
                } catch (IOException e) {
                    Log.e("Hub", "Error getting the image from server : " + e.getMessage().toString());
                }
            }

            return marry;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mprogressDialog.setMessage("Loading Image...");
            mprogressDialog.show();
        }

        @Override
        protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected void onPostExecute(ArrayList<Bitmap> bitmaps){
            super.onPostExecute(bitmaps);
            mImageView.setImageBitmap(marry.get(0));
            vImageView.setImageBitmap(marry.get(1));
            nImageView.setImageBitmap(marry.get(2));
            iImageView.setImageBitmap(marry.get(3));
            mprogressDialog.dismiss();

        }
    }

     

No comments:

Post a Comment