Saturday, 21 May 2011

Android - Advanced message sending

This post explain very good how to send and receive message inside a threat:
http://www.aviyehuda.com/2010/12/android-multithreading-in-a-ui-environment/

There are some point that I want to state:
  • Looper: After the method Looper.loop(), not code should be placed because they are not going to be executed. This is because the class Lopper convert a threat into a non-stop loop, which allow the code to be prepared between the method Looper.prepare() and the method Looper.loop(), but the method Lopper.loop() never stops.
  • Looper: As the official developer reference has pinpoint, the method handleMessage (Message msg) could be modified. The clear code is:
public Handler mHandler;
new Thread (new Runnable() {
    @Override
    public void run() {
        Looper.prepare();
        mHandler = new Handler() {
            pubic void handleMessage( Message msg) {
                // process incoming messages here
            }
        };

        Looper.loop();
    }
}
  • Looper: Between the method Looper.prepare() and the method Looper.loop(), other sentences could be used. For example, the code could invoke a new class which use the handler as input parameter.
  • Looper: The handler could be set as general variable that is used inside the program. Because we are using a threat to set value on it, the main threat doesn't know when the value of it is set. If it is invoked before the value is set, a "NullPointer" exception could appear. To avoid it, I recommend to user a loop in the main threat that check the value of it. For example
while (handler == null) {}

More information about Loop and handler:
Official android development reference (Looper): http://developer.android.com/reference/android/os/Looper.html
Android Guts: http://mindtherobot.com/blog/159/android-guts-intro-to-loopers-and-handlers/
Just do It: http://rxwen.blogspot.com/2010/08/looper-and-handler-in-android.html

No comments:

Post a Comment