Android Handler.handleMessage()不会被调用

时间:2014-12-19 09:58:30

标签: java android multithreading handler runnable

我试图理解这个版本的Message.obtain() http://developer.android.com/reference/android/os/Message.html#obtain%28android.os.Handler,%20java.lang.Runnable%29

传递给Message.obtain()的Runnable肯定会被调用, 但未调用Handler.handleMessage()(在msg.sendToTarget()或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();
}

1 个答案:

答案 0 :(得分:3)

我们来看看Message class:

中的这个方法

public Runnable getCallback()

  

检索将在此消息发生时执行的回调对象   处理。该对象必须实现Runnable。 这是由   正在接收此消息以发送它的目标处理程序。如果不   设置,消息将被分派给接收处理程序   的handleMessage(消息)

以及您要求获得Message

的内容
public static Message obtain (Handler h, Runnable callback)

因此,因为您设置了回调handleMessage(Message)未被调用: - )