Saturday, 21 May 2011

Android - Advanced message sending

This post explain very good how to send and receive message inside a threat:

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() {
    public void run() {
        mHandler = new Handler() {
            pubic void handleMessage( Message msg) {
                // process incoming messages here

  • 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):
Android Guts:
Just do It:

No comments:

Post a Comment