Handler是很灵活的一个类,当运行下面的代码时:
new Handler().post(new Runnalbe(){ @Override public void run(){ //do something }});
它内部干了些啥?!
找到它的源代码:
/** * Causes the Runnable r to be added to the message queue. * The runnable will be run on the thread to which this handler is * attached. * * @param r The Runnable that will be executed. * * @return Returns true if the Runnable was successfully placed in to the * message queue. Returns false on failure, usually because the * looper processing the message queue is exiting. */ public final boolean post(Runnable r) { return sendMessageDelayed(getPostMessage(r), 0); }
sendMessageDelayed(getPostMessage(r), 0)的含义是立即发送了一个消息,再来看getPostMessage(r)的定义:
private static Message getPostMessage(Runnable r) { Message m = Message.obtain(); m.callback = r; return m; }
总结:Runnalbe()的代码执行在Handler定义的线程中。