Sunday, July 11, 2010

Android Handler

Message Handler
I have started looking into Android.

I have tried to build a utility class that can do Network I/O. And grasping things was little hard at first. Network I/O or other heavy-duty stuff in Android should be done on other worker thread. Because doing it in main thread (or the UI thread) can ( and will ) make your application unresponsive and may be killed as the system is persuaded to think that it has hung. For every Android developer, this is a must-read.

So you have to do the long running operations in separate thread. And to interact between threads you have to resort to Handler. A Handler is used to send message or runnable to a particular thread. The thing to remember is that a Handler is associated with the MessageQueue of the single thread which has created it. After creating a Handler, it can be used to post message or runnable to that particular thread.

Here is an example

  1. public class MyActivity extends Activity {

    void startHeavyDutyStuff() {

    // Here is the heavy-duty thread
    Thread t = new Thread() {

    public void run() {
    while (true) {

    mResults = doSomethingExpensive();

    //Send update to the main thread
    messageHandler.sendMessage(Message.obtain(messageHandler, mResults)); }}};

    // Instantiating the Handler associated with the main thread.
    private Handler messageHandler = new Handler() {

    public void handleMessage(Message msg) {
    switch(msg.what) {
    //handle update