user1437328
user1437328

Reputation: 15846

Android Handler.handleMessage() won't get called

I'm trying to understand this version of Message.obtain() http://developer.android.com/reference/android/os/Message.html#obtain%28android.os.Handler,%20java.lang.Runnable%29

The Runnable passed to Message.obtain() is called for sure, but the Handler.handleMessage() defined is not called (on msg.sendToTarget() or even mHandler.sendMessage(msg))

Handler mHandler;

class MyThread implements Runnable {

  @Override
  public void run() {
    Message msg = Message.obtain(mHandler, new Runnable() {
        @Override
        public void run() {
            System.out.println("This is printed for sure"); // This is printed for sure
        }
    });

    msg.obj = "My message!";

    msg.sendToTarget();
  }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  mHandler = new Handler() {
      @Override
      public void handleMessage(Message msg) {
          System.out.println(msg.obj); // This is never printed
      }
  };

  Thread t = new Thread(new MyThread());
  t.start();
}

Upvotes: 2

Views: 4288

Answers (1)

mmlooloo
mmlooloo

Reputation: 18977

Let' s take a look at this method from Message class:

public Runnable getCallback ()

Retrieve callback object that will execute when this message is handled. This object must implement Runnable. This is called by the target Handler that is receiving this Message to dispatch it. If not set, the message will be dispatched to the receiving Handler's handleMessage(Message).

and what you have called to obtain a Message

public static Message obtain (Handler h, Runnable callback)

So because you set the callback handleMessage(Message) is not called :-)

Upvotes: 3

Related Questions