Amazon Gift Cards

Monday, January 5, 2009

Using Handler in Android

If you come from a Javascript/Actionscript 1 or 2, you probably know setInterval coz you need to use it a lot, in Android there are several ways in making your setInterval, one of which is using a Handler with Thread or using Timer, on this article would focus on using Handler. The reference of where i learn this is on your android sdk folder, under the samples, there is an app named Snake.java. You can take a look at that one and see more advance than the codes below.
package com.monmonja.firstDemo;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

public class Main extends Activity  { 
  private TextView txtStatus;
  private RefreshHandler mRedrawHandler = new RefreshHandler();

  class RefreshHandler extends Handler {
    @Override
    public void handleMessage(Message msg) {
      Main.this.updateUI();
    }

    public void sleep(long delayMillis) {
      this.removeMessages(0);
      sendMessageDelayed(obtainMessage(0), delayMillis);
    }
  };

  private void updateUI(){
    int currentInt = Integer.parseInt((String) txtStatus.getText()) + 10;
    if(currentInt <= 100){
      mRedrawHandler.sleep(1000);
      txtStatus.setText(String.valueOf(currentInt));
    }
  }

  @Override 
  public void onCreate(Bundle icicle) { 
    super.onCreate(icicle); 
    setContentView(R.layout.main);
    this.txtStatus = (TextView) this.findViewById(R.id.txtStatus);
    updateUI();
  } 
}



Quick Explanation
This one is probably the most hardest for me to explain so far, okay so here is how it goes. We created a class inside our Activity that extends Handler, now on this handler we override handleMessage so what we can use this Handler to handle our messages to it. We then declare a sleep function to delay another execute of this handler with the function sendMessageDelayed. Now on our updateUI we set our own codes and call mRedrawHandler.sleep(1000); to delay our message. But before all of this to happen on our onCreate function we call updateUI to start updating our textfield.


Hope it helps and hope i'm not wrong with my explanations.

16 comments:

felipe said...

hey man, very good your example, I am following it!

Rames said...

Thank you very much for this tut...

Ektopil said...

Wow, thats what I was looking for all the time.

naresh said...

how can we stop this handler to execute. pls tell me, its urgent

Sudhakar Chavali said...

I was really confusing and made me panic, in managing UI thread with my custom threads.

This approach helped me alot.

Thanks for the post

Best Regards
Sudhakar Chavali

Keerthy said...

Nice you can visit this site also http://android-codes-examples.blogspot.com/2011/03/how-to-run-runnable-thread-or-ui-thread.html

Anonymous said...

Amazing, although I'm not fully understand, it works.
Thanks

Clint said...

Great work, thanks for posting this. Any suggestions on implementing this as a session timeout / redirect?

Something like...

> User logs in
> Timer starts
> New activity spawns and restarts the timer
> No action happens and timer elapses
> User is redirected to the login screen

ASHISH ANAND said...

amazing work Dude!!

Anonymous said...

when i test it, it says force close on my phone, can you post the rest of the files that go with this? what version of android should i be using in eclipse?

Almond said...

you could remove
this.txtStatus = (TextView) this.findViewById(R.id.txtStatus);
and replace
txtStatus.setText(String.valueOf(currentInt));
with
Log.d("test",String.valueOf(currentInt));
and on your terminal type
adb logcat

Kambhakth said...

Hey Man, Thanks for this efficient and simple tutorial. i was looking for updating the UI for regular intervals. This doesn't put much load on the UI thread and is efficient way of doing it.

Blurred said...

Great example, Thanks. Is there any way implement an interface in the Main Activity Class that does the same without the need of creating a RefreshHandler class?

Anonymous said...

it just force closes every time it sends the first message...

Tugrul said...

Hey man very good. Thank you very much. That's it what I want...

Unknown said...

Erron in "Main"