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.
Post a Comment