我试图理解这个版本的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();
}
答案 0 :(得分:3)
我们来看看Message
class:
public Runnable getCallback()
检索将在此消息发生时执行的回调对象 处理。该对象必须实现Runnable。 这是由 正在接收此消息以发送它的目标处理程序。如果不 设置,消息将被分派给接收处理程序 的handleMessage(消息)强>
以及您要求获得Message
public static Message obtain (Handler h, Runnable callback)
因此,因为您设置了回调handleMessage(Message)
未被调用: - )