Tuesday, October 19, 2010

Using Handler in Android

 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.


Main.java
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();
  }
}


main.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">

<TextView android:id="@+id/txtStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:textSize="20px"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true">
</TextView>
</RelativeLayout>



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.

Your Ad Here