Android App Development:Threading part 1: Handlers

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.


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() {
  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. */
 public void onCreate(Bundle savedInstanceState) {

 protected void onStart() {
              // create a new thread
  Thread background=new Thread(new Runnable() {

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

// send message to the handler with the current message handler          

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


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() {
  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

 /** Called when the activity is first created. */
 public void onCreate(Bundle savedInstanceState) {
  txt = (TextView) findViewById(;

 protected void onStart() {
  // create a new thread
  Thread background = new Thread(new Runnable() {

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


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 method like this:

Runnable r=new Runnable() {

   public void run() {


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.

examsheets – braindumps – selftestengine – certkiller – testking –

22 Responses to “Android App Development:Threading part 1: Handlers”

  1. riptaape 23. Mar, 2012 at 4:47 am #

    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!

  2. Android Research 30. Mar, 2012 at 7:10 am #

    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.

  3. heathnieveseod 08. Apr, 2012 at 7:41 pm #

    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

  4. gomnemive 16. Apr, 2012 at 2:56 pm #

    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

  5. Fleeceirerwop 17. Apr, 2012 at 2:03 pm #

    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

  6. BicLinoEnlilk 16. May, 2012 at 1:41 pm #

    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.

    Achieve better exposure in search engines.

  7. ewoks 12. Jun, 2012 at 3:20 am #

    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 12. Jun, 2012 at 3:21 am #

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

  8. Best of Android 14. Aug, 2012 at 2:04 pm #

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


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

  9. Android Example 04. Feb, 2013 at 12:52 am #

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

    I have got some good links


  10. amnesia a machine for pigs download 19. Apr, 2013 at 12:02 pm #

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

  11. Muhammad Zohaib 20. Apr, 2013 at 4:40 pm #

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

  12. tunahan 20. Jun, 2013 at 11:13 am #

    this tutorial is very useful. thanks

  13. breast actives before and after 29. Jun, 2013 at 9:12 pm #

    Great article. I am experiencing many of these issues as

  14. praveen 30. Jul, 2013 at 4:31 am #

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

  15. Praveen 24. Sep, 2013 at 1:38 am #

    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..

  16. Android App Development 25. Sep, 2013 at 2:10 am #

    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 !

  17. Thomas 18. Oct, 2013 at 4:42 pm #

    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.


  1. Android App Development:Threading part 2: Async Tasks | blog - 08. Dec, 2011

    [...] the previous post we saw one way to deal with threads in Android, which is by using Handlers. In this post we’ll [...]

  2. copy watch tag - 10. Feb, 2012

    [...] watch replica manufacturers copy watch chopard james bond replica watch replica watch uk paypal Copy watch in uk watch the clone wars Replica watch germany watch replica u-boat watch replica hong kong watch replica jacob co watch replica comparison michael kors watch copy Replica watch 99 Watch replica japan replica watch paypal watch clone tv show online swiss clone watches replica watch kuwait replica clock face Replica watch germany michael kors watch copy Copy watch germany watch clone tv show online copy watches replica watch 88 Other site about "watch replica tag heuer": watch replica top site, replica clock manufacturer, watch replica vintage [...]

  3. Android App Development:Threading part 2: Async Tasks - 05. Apr, 2012

    [...] the previous post we saw one way to deal with threads in Android, which is by using Handlers. In this post [...]

  4. Unable to call arraylist in another activity using AsyncTask- Android app : Android Community - For Application Development - 06. Mar, 2013

    [...] can use Messages and Handlers here. Take a look at this article: You can send a message from another thread, containing ArrayList. And then handle this message in [...]

Leave a Reply

© 2008-2051 • Mobile Orchard and the Bar-Tree Logo are service marks. ContactAdvertise