Thursday, 3 November 2011

TYPES OF THREAD MECHANISM IN ANDROID

Thread mechanism in Android is a very good topic for the beginner who wishes to start building a good android application with good responsive time and which runs without too much hangout our app. Generally, this features create a nice end user experience and it will lead acceptance level of apps at very high level, and our clients be happy by using our well responsive application.

So before we start on Android thread mechanism, let us first see some points why we need it in our app?, and without it, Is possible to make our app development easy ? so the some points are coming into my mind are as follows...
  • Android developer team given us Designing Standards and according to that by following those steps we make very high level app experience.
  • Sometimes our application functionality wants to do some tough and time consuming calculations and at that time we are not able to handle all the task done at single thread model, and finally our app leads to unresponsive to end user experience.
  • So the very time consuming work needs to be done at separate user interface thread.
  • Every android application having one "Main" thread. Each of which runs on main user interface thread model and every process needs to communicate with the main thread for successfully tasks implementation. if our processes takes more than of 5 seconds to response to the main thread then android system generates ANR ("Android Not Responding") dialog box like this one...
[Fig:- Android Not Responding Dialog]
  • So the very first reason of using separate thread mechanism in long running calculations is to avoid ANR in our app.
  • Second reason of using thread is that in Game application there were lots of objects communicating to each other and working concurrently at that time we needs to use separate  thread model for updating Game User Interfaces.
  • So the final conclusion for "Why we need Thread in our app?", is that For better responsiveness, For better calculating long running task[Such as Network or Database Operations, Long running services and Updating Location of the User] at separate of Main thread and also to avoid Android ANR dialogs for good end user experiences.

So, by just reading above, We needs to understand one of the thread mechanism available in android and how many types of thread an android provided to developer of the app in sdk, so the answer of this question provided below as per my knowledge...
  1. Android SDK inherits directly Java Thread.
  2. Android Handler Thread.
  3. AsyncTask class thread.
"Android SDK inherits directly Java Thread"
  • Android app developer can directly use the thread available in Java by inheriting package called "java.util.concurrent".
  • This mechanism used only when we need to do some background task without updating user interfaces on this thread, because android does not provide updating User Interface from non Android thread like this one. So this is the drawback. So for overcoming this mechanism android provides some another thread mechanism called "Handler" thread.
"Android Handler Thread"
  • In android Handler is the class given by the sdk, it is used for concurrency, and also updates user interfaces at each time, and also communicate with the Main thread of the application.
  • A handler provides a method for receiving messages and runnable.
  • We requires only one handler object for starting thread and sending result back to handler message queue.
  • So finally... “A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue.”
  • How to use handler in our app... so the code snippets give below...
package com.HelloWorkShopFromGaurangDhorda;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.widget.TextView;

/**
 * This is a simple activity that demonstrates the Handler Thread mechanism.
 *
 */
public class HandlerThreadDemo extends Activity implements Runnable{
   
    private TextView textView;
    private Handler handler;
    private Thread thread;
   
//Methods
/**
 * onCreate - called when the activity is first created.
 * This is where you should do all of your normal static set up: create views, bind data to lists, etc.
 * This method also provides you with a Bundle containing the activity's previously frozen state, if there was one.
 *
 * Always followed by onStart().
 *
 */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pd);
        handler = new Handler();
        textView = (TextView) findViewById(R.id.textView);
        textView.setText("Press Any key to start calculation...");
    }
    /**
 * In response to the being clicked, on any of the screen area of the app this will start a background task 
 * The results will be displayed on the screen.
 *
 * @param keyCode int
 * @param KeyEvent event
 * @return keyCode, event
 */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
            thread = new Thread(this);
            thread.start();
            return super.onKeyDown(keyCode, event);
    }
    /**
 * Perform the task, which is to compute a simple loop through up to 100 and report progress on the UI thread.
 * Return each loop values to UI thread and Main Thread running as per this values...
 *
 */
    @Override
    public void run() {
        try{
            for (int i=1;i<=10;i++){
                objHandler.sendEmptyMessage(i);
                Thread.sleep(2000);
            }
        }
        catch(InterruptedException e){
            e.printStackTrace();
        }
    }
    /**
 * Takes values from run() method by obj.Handler.sendEmptyMessage(i) and values of i will be passes on     *  msg parameter and after that msg parameter is being converted into String object.
 * Return each loop values to UI thread and Main Thread running as per this values... by updating simple     *  TextView values...
 *
 */
    private Handler objHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
                String s=msg.toString();
                textView.setText("calculation completed at :- " + s);
        }
    };
}  

"AsyncTask class thread" 
  • Android AsyncTask Class takes care of Thread management in our application. We must have to extends "AsyncTask" class in our main class activity so that this separate class`s task can be converted into background working model without interfering to main thread....
  • Here main difference in "Handler and AsyncTask" class is that 
    • while running thread in void run() method in handler class we need to pass message to handler class and then we pass that values to main user interface thread.
    • In AsyncTask class android takes care of all thread calling mechanism. So, developer not need to remember anything at all. All calling process done by AsyncTask class. 
  1. Instance of AsyncTask needs to be created in UI thread. Also execute method with parameters should be called from UI thread.
  2. Methods onPostExecute(), onPreExecute() and onProgressUpdate() should not be explicitly called.
  3. Task can be executed only once. 
  • So above points needs to be remember in mind before we apply AsyncTask Class...
  • An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute(), doInBackground(), onProgressUpdate() and onPostExecute().
  • onPreExecute() :- his method is called before doInBackground method is called.
  • doInBackground() :- long running operation goes in this method. When onClick method is executed on click of button, it calls execute method which accepts parameters and automatically calls doInBackground method with the parameters passed. 
  • onProgressUpdate():- This method is invoked by calling publishProgress anytime from doInBackground call this method.
  • onPostExecute():- This method is called after doInBackground method completes processing. Result from doInBackground is passed to this method.
  • We will put one example which we already implemented above for handler...
"code for AsyncTask Demo"

package com.HelloWorkShopFromGaurangDhorda;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

/**
 * This is a simple activity that demonstrates the "AsyncTask" Thread mechanism.
 *
 */

public class AsyncTaskDemo extends Activity implements OnClickListener{
    private TextView textView;
    private Button btnClick;

//Methods
/**
 * onCreate - called when the activity is first created.
 * This is where you should do all of your normal static set up: create views, bind data to lists, etc.
 * This method also provides you with a Bundle containing the activity's previously frozen state, if there was one.
 *
 * Always followed by onStart().
 *
 */


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pd);
        textView = (TextView) findViewById(R.id.textView);
        textView.setText("Press Any key to start calculation...");
        btnClick = (Button) findViewById(R.id.btnClick);
        btnClick.setOnClickListener(this);
    }
   
    /**
 * Perform the task,By clicking button from user interface.

 */
    @Override
    public void onClick(View arg0) {
       
        new asyncdemo().execute(1,1,1);
    }

 /**
 * Asyncdemo class that extends AsysncTask class and it passes 3 Integer Generics types.
* Whole task of  thread is done by android system.
* doInBackground method is automatically called by involing "new asyncdemo().execute(1,1,1);"
* send result back to onProgressUpdate() method by calling publishProgress(i), method in doInBackground * method.
* Automatic updates User Interface and communicate with Main Android Thread...

 */
    public class asyncdemo extends AsyncTask<Integer,Integer,Integer>{

        @Override
        protected Integer doInBackground(Integer... params) {
            // TODO Auto-generated method stub
            int values=0;
           
            try{
            for (int i=1;i<=10;i++){
                publishProgress(i);
                values+=i;
                Thread.sleep(2000);
            }
            }
            catch(InterruptedException e){
                e.printStackTrace();
            }
            return values;
        }
        protected void onProgressUpdate(Integer... progress) {
             textView.setText(progress[0].toString());
         }
       
    }//end of asyncclass...
}// end of main class...

"Final Conclusion"
  • Avoid the Jank (make sure your application is responsive)
    • Don’t block the UI thread
    • Offload long running tasks to background threads
    • Using AsyncTask or ServiceIntent
    • Keep user notified about progress
"I Hope this helps you in better understanding of Thread mechanism available in android sdk and   why we need it in our app?..."

No comments:

Post a Comment