1.Handler的post(Runnable)方法
2.Runnable的运行机制
3.post方法和sendMessage方法的区别
1.Handler的post(Runnable)方法
1 public static class PlaceholderFragment extends Fragment { 2 3 private Button button; 4 private Handler handler = new Handler(); //没有像以前那样写MyHandler方法 5 6 public PlaceholderFragment() { 7 } 8 9 @Override 10 public View onCreateView(LayoutInflater inflater, ViewGroup container, 11 Bundle savedInstanceState) { 12 View rootView = inflater.inflate(R.layout.fragment_main, container, false); 13 14 button = (Button)rootView.findViewById(R.id.buttonId); 15 button.setOnClickListener(new OnClickListener() { 16 @Override 17 public void onClick(View v) { 18 TestThread tt = new TestThread(); 19 tt.start(); 20 } 21 }); 22 23 return rootView; 24 } 25 26 class TestThread extends Thread{ 27 28 @Override 29 public void run() { 30 Runnable r = new Runnable() { 31 @Override 32 public void run() { 33 Log.i("tag","CuurentThread--->" + Thread.currentThread().getName()); 34 } 35 }; 36 handler.post(r); 37 } 38 } 39 }
打印结果很劲爆
意味着Runnable竟然运行在主线程中!!!
看源码, Handler的post方法
1 public final boolean post(Runnable r) 2 { 3 return sendMessageDelayed(getPostMessage(r), 0); 4 }
先看getPostMessage(r)
1 private static Message getPostMessage(Runnable r) { 2 //该方法完成两个操作:1、生成了一个Message对象。2、将r赋值给Message的callback属性 3 Message m = Message.obtain(); 4 m.callback = r; //Message的callback属性 5 return m; 6 }
因此Handler的post方法相当于下面
1 public final boolean post(Runnable r) 2 { 3 //return sendMessageAtTime(getPostMessage(r), 0); 4 Meesage msg = getPostMessage(r); 5 return sendMessageDelayed(msg, 0); 6 }
上述中sendMessageDelayed是干嘛的呢
1 * Enqueue a message into the message queue after all pending messages 2 * before (current time + delayMillis). You will receive it in 3 * {@link #handleMessage}, in the thread attached to this handler. 4 * 5 * @return Returns true if the message was successfully placed in to the 6 * message queue. Returns false on failure, usually because the 7 * looper processing the message queue is exiting. Note that a 8 * result of true does not mean the message will be processed -- if 9 * the looper is quit before the delivery time of the message 10 * occurs then the message will be dropped. 11 */ 12 public final boolean sendMessageDelayed(Message msg, long delayMillis) 13 { 14 if (delayMillis < 0) { 15 delayMillis = 0; 16 } 17 return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis); 18 }
也就是延迟发送, 当delayMillis=0即相当于直接发送
综上:生成一个Message对象, 将r赋值给Message对象的callback属性, 然后再将Message对象放置在消息队列当中
Looper取出了携带有r对象的Message对象之后, 调用dispatchMessage方法, 判断Message的callback属性是否有值, 此时callback属性有值,
所以执行了handCallback(Message msg),在该方法中执行msg.callback.run();
TestThread中从网络取回数据, 定义一个Runnable对象, 在其run()方法中直接写更新UI的代码,
再用主线程中生成的handler进行post出去, post方法中生成Message对象, r赋值给Meesage的callback属性,
Message放入消息队列之中, Looper取出, 调用dispatchMessage方法,
在dispatchMessage中调用handlercallback方法, 在handlercallback中会执行Runnable的run()方法。
因为Looper在主线程, 所以dispatchMessage啊, handlercallback啊, 也都会在主线程.同样run()方法也是的