Android App Development:Threading part 1: Handlers

By
On May 4, 2011

Multi-Threading concept is essential in most platforms. it provides maximum utilization of the processor. threading is used when the program executes time consuming processes (such as calling a web service) and to give a good user experience by unblocking the UI.

Android provides threading techniques to perform time consuming tasks in a background thread with coordination with the UI thread to update the UI.

Android provides the following methods of threading:

  1. Handlers.
  2. Async. Tasks.

Handlers:

When you create an object from the Handler class, it processes

Messages and Runnable objects associated with the current thread MessageQueue. the message queue holds the tasks to be executed in FIFO (First In First Out) mannser. you will need only ine Handler per activity where the background thread will communicate with to update the UI.

The Handler is associated with the thread from which it’s been created

We can communicate with the Handler by two methods:

  1. Messages.
  2. Runnable objects.

In this post we will demonstrate how to use both using a simple example which is updating the text of a TextView using multiple threads.

Using Messages:

The steps of using a Handler are as follows:

  1. You create a Handler object with an asscociated callbackmethod to handle the received messages (it is the method where the UI updatewill be done).
  2. From the background thread you will need to send messages to thehandler.

Here’s the code of our activity:

public class MainActivity extends Activity {
TextView txt;
// our handler
 Handler handler = new Handler() {
  @Override
  public void handleMessage(Message msg) {
//display each item in a single line
  txt.setText(txt.getText()+"Item "+System.getProperty("line.separator"));
     }
 };

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  txt=(TextView)findViewById(R.id.txt);
 }

 @Override
 protected void onStart() {
  super.onStart();
              // create a new thread
  Thread background=new Thread(new Runnable() {

   @Override
   public void run() {
    for(int i=0;i<10;i++)
    {
     try {
      Thread.sleep(1000);        b.putString("My Key", "My Value:

"+String.valueOf(i));
// send message to the handler with the current message handler

handler.sendMessage(handler.obtainMessage());
     } catch (Exception e) {
      Log.v("Error", e.toString());
     }
    }
   }
  });

  background.start();
 }
}

After running the following code the TextView will display the following,

Each second a new line is written:


This example is pretty basic, it just sends the same message for a number of times.

What if we want the message sent to hold data that’s changed each time the message is sent, the answer is to use Message.setData(Bundle bundle) method by creating a Bundle object and adding the data to it like this:

public class MainActivity extends Activity {
 TextView txt;
 // our handler
 Handler handler = new Handler() {
  @Override
  public void handleMessage(Message msg) {
   // get the bundle and extract data by key
   Bundle b = msg.getData();
   String key = b.getString("My Key");
   txt.setText(txt.getText() + "Item " + key
   +System.getProperty("line.separator"));
  }
 };

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  txt = (TextView) findViewById(R.id.txt);
 }

 @Override
 protected void onStart() {
  super.onStart();
  // create a new thread
  Thread background = new Thread(new Runnable() {

   @Override
   public void run() {
    for (int i = 0; i < 10; i++) {
     try {
      Thread.sleep(1000);
                                        Message msg = new Message();
      Bundle b = new Bundle();
      b.putString("My Key", "My Value: " + String.valueOf(i));
      msg.setData(b);
      // send message to the handler with the current message handler
      handler.sendMessage(msg);
           } catch (Exception e) {
      Log.v("Error", e.toString());
     }
    }
   }
  });

  background.start();
 }
}

We put a string to the bundle and send a message with that bundle. in the handler method we receive the bundle and get the value with the predefined key.

After executing that code the text view would look like this:


Using Runnables:

another way to use Handlers is to pass them a Runnable by using the

Handler.post() method like this:

Runnable r=new Runnable() {

   @Override
   public void run() {
    txt.setText("Runnable");

   }
  };

  handler.post(r);

This will add the Runanble object to the message queue to be executed by the handler.

Sending Messages in a timely manner:

we can use handlers to send messages or post runnables at time intervals using

The following methods:

  1. handler.sendEmptyMessageAtTime(int what,long uptimeMillis):sends an
    empty message at a specific time in milli-seconds, can be defined by using the
    SystemClock.uptimeMillis() method to get the time since the device boot
    in milli-seconds and concatinating to it.
  2. handler.sendEmptyMessageDelayed(int what,long delayMillis):sends an
    empty message after a certain amount of time in milli-seconds.
  3. handler.sendMessageAtTime(Message msg,long uptimeMillis).
  4. handler.sendMessageDelayed(Message msg,long delayMillis).
  5. handler.postAtTime(Runnable r,long uptimeMillis).
  6. handler.postAtTime(Runnable r,Object token,long uptimeMillis):posts a
    runnable with an object as a distinguishing token.
  7. handler.postDelayed(Runnable r,long delayMillis).

All the above messages return a boolean indicating whether the message or the runnable has been placed successfully in the message queue.

Removing Call backs:

If you want to remove a runnable or a message from the message queue, you can use the following methods:

  1. handler.removeCallbacks(Runnable r).
  2. handler.removeCallbacks(Runnable r,Object token).
  3. handler.removeCallbacksAndMessages(Object token).
  4. handler.removeMessages(int what).
  5. handler.removeMessages(int what,Object object)

That’s was all about handlers, stay tuned for another tutorial next week.

  • Pingback: Android App Development:Threading part 2: Async Tasks | blog

  • Pingback: copy watch tag

  • http://rip60s.com riptaape

    rip 60 The weeks get gradually harder, but I found week 6 to be the hardest! definitely not week Several or 8-10, There is also a recovery week that’s just a lot of stretching with the help of the suspension trainer! Each workout features a warm up and cool down, The actual workouts are run by a guy named Jeremy Strom whom I didn’t find great!
    rip 60 FAQs
    rip 60 stories
    rip60 reviews
    rip60 nutrition
    about rip60
    I have found that to be so useful for me! We’m capable of complete my personal entire exercise routine even if I actually’m owning an ‘off’ time and was struggling for getting through the workout!
    rip60

  • http://androidresearch.wordpress.com/ Android Research

    Hi,
    Thank you for posting this tut.
    I have read several tutorials about Handlers before, but some were talking only using Messages, while others were talking only using Runnables. This was a bit confusing for me.
    You really cleared up things for me.

  • Pingback: Android App Development:Threading part 2: Async Tasks

  • heathnieveseod

    Select a single-syllable name which includes a tough sound i.
    No longer are women restricted to black watches, but can now have a very plethora of possibilities which include don’t just any color on the rainbow, but patterns also.
    Until you intend to make use of this pattern solely with white shirts, prior experience with matching neckties to shirts is often a need to.
    Term spread easily that Edward’s capes could stand up to the monsoon rains that wore down each and every sailor, retaining them warm and dry.
    Grab A Duplicate Click here.

    armani ceramica 1410
    armaniwatchese.com

  • gomnemive

    Moreover, a repp or striped necktie hyperlinks back again to far more conservative traditions in men’s trend, whatever the shade may be.
    But there is 1 brand that can let you come to feel truly superior, which is the Moncler jacket and coat.
    Should you have a pet cat, you will not have considerably difficulties grooming them simply because they essentially keep on their own clear.
    The economic cost of Asianfashion4u.
    Just after viewing, it’s possible you’ll sense assured adequate to attempt it oneself following time.

    Authentic Hockey Jersey

  • http://www.de-cartier.com Fleeceirerwop

    com.
    Maintain the suggestions in the collar underneath your suit nevertheless the complete collar even now visible previously mentioned your suit lapels, and you also really should appearance quite darn sharp in the course of the day.
    This is also very handy if the client wants to share the cost with a second party as two doors create separate compartments.
    About e-MDse-MDs is really a primary developer of integrated electronic clinical data and apply administration application for physician practices and enterprises.
    Wool Pea Coat For your NavyA pea coat goes by more than one identify, which include pea jacket in some cases.

    Authentic Hockey Jersey

  • BicLinoEnlilk

    Hi, every one, I hope this particular sharing could possibly provide value to you.

    Articles will be reviewed almost every 11 hrs.

    Distribute your content to PR4, fast-acceptance article directory. Allow exclusively your excellent content.

    http://bit.ly/J8iWGF

    Achieve better exposure in search engines.

  • ewoks

    great tutorial..
    however seriously rethink about using some comments spam filtering plugin or whatever that can stop ruining follow up of ur articles.. Cheers

    • ewoks

      if u ever manage to see my comment.. ;)))

  • http://www.bestofandroid.com/ Best of Android

    Very useful info for newbie android developers. Thank you very much.

    ———–

    Dhanaiah
    Best of Android | Android News | Best Android Apps | Android Games | Android Devices

  • http://androidexample.com Android Example

    Nice Thread Tutorial, i am new in android , its help me a lot …

    I have got some good links

    Thread_With_Handlers

  • Pingback: Unable to call arraylist in another activity using AsyncTask- Android app : Android Community - For Application Development

  • http://aamfp.blogspot.com/ amnesia a machine for pigs download

    Pretty! This was an incredibly wonderful post.
    Thanks for providing this info.

  • Muhammad Zohaib

    this Code gives No Out Put In TextView Whats This matter Help Me On This Issue…

  • http://www.tunahanilhan.com tunahan

    this tutorial is very useful. thanks

  • http://www.youtube.com/watch?v=Ow-uKTnhkic breast actives before and after

    Great article. I am experiencing many of these issues as
    well..

  • praveen

    Excellent Tutorial..But you could have given an example same as with Handler for Runnable class also..

  • Praveen

    Great article… Could you please explain is there any difference in using Handing post Runnable or Send message. What are the differences in between these two methods and which one is performance wise beneficiary..

  • http://www.tanzaniteinfotech.com/mobile-app/android-application-development/ Android App Development

    Really nice guide of Handlers which is associated with Messages and Runnable. These are the basic things to know as a android app developer. Thanks for sharing !

  • Thomas

    I’ve been having some trouble getting handlers/etc. working right and this page provides exactly what I wanted to start off with. It’s been very helpful. Thanks a lot.

  • http://www.amazon.com/dp/B00GHLWKUY/ www.amazon.com

    Hi there, I found your web blog by means of Yahoo and google when evaluating the same matter, your site got here right up, this indicates wonderful. I’ve book-marked for you to favourites features and functions|added to the bookmarking.

    • http://www.friv200.com friv

      Very good and has many improvements and exciting new.

  • http://www.justtotaltech.co.uk/ android app development

    Such an informative article, Thanks for sharing this information, i am also suffering from these issues, will get advantage from this