1. 前言
上篇文章介绍了几种hanlder创建方式,其实这种使用方式大家都知道,但是为什么可以这么做,可能很多人不知道,至少不清楚,网上很多文章也是到处粘贴,听别说handler把Message发送到MessageQueue里面去,Looper通过死循环,不断从MessageQueue里面获取Message处理消息,因为Mesage.target就是当前hanlder,所以最后转到handleMessage()方法中去处理,整个流程是这样。其实大概都是对的,之前面试的时候,我也都是这么说,也没有面试官深入问过,这次正好有时间深入源码系统学习下,毕竟还是要知其所以然。
2.使用方法
package com.example.test.myapplication;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.widget.Toast;public class MainActivity extends Activity { private Handler handler1 = new Handler() { @Override public void handleMessage(Message msg) { if (msg.arg1 == 1) { Toast.makeText(MainActivity.this, "hanlder1", Toast.LENGTH_SHORT).show(); } super.handleMessage(msg); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new Thread(new Runnable() { @Override public void run() { Message message = handler1.obtainMessage(); message.arg1 = 1; handler1.sendMessage(message); } }).start(); } }
这种用法是大家最常用的,下面我们就用这个来作为切入点。
3.源码讲解
1)Looper,MessageQueue创建
应用启动的时候会先调用ActivityThread的main方法,main方法会调用Looper.prepareMainLooper();创建Looper对象,Looper对象的构造方法中会创建MessageQueue对象,源码如下所示:
public static void main(String[] args) { Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain"); SamplingProfilerIntegration.start(); // CloseGuard defaults to true and can be quite spammy. We // disable it here, but selectively enable it later (via // StrictMode) on debug builds, but using DropBox, not logs. CloseGuard.setEnabled(false); Environment.initForCurrentUser(); // Set the reporter for event logging in libcore EventLogger.setReporter(new EventLoggingReporter()); AndroidKeyStoreProvider.install(); // Make sure TrustedCertificateStore looks in the right place for CA certificates final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId()); TrustedCertificateStore.setDefaultUserDirectory(configDir); Process.setArgV0(""); Looper.prepareMainLooper(); ActivityThread thread = new ActivityThread(); thread.attach(false); if (sMainThreadHandler == null) { sMainThreadHandler = thread.getHandler(); } if (false) { Looper.myLooper().setMessageLogging(new LogPrinter(Log.DEBUG, "ActivityThread")); } // End of event ActivityThreadMain. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); Looper.loop(); throw new RuntimeException("Main thread loop unexpectedly exited"); }
在第23行可以看到Looper.prepareMainLooper();方法,此方法其实就是UI线程默认为应用创建Looper对象,我们继续看下prepareMainLooper()方法的源码:
public static void prepareMainLooper() { prepare(false); synchronized (Looper.class) { if (sMainLooper != null) { throw new IllegalStateException("The main Looper has already been prepared."); } sMainLooper = myLooper(); } }private static void prepare(boolean quitAllowed) { if (sThreadLocal.get() != null) { throw new RuntimeException("Only one Looper may be created per thread"); } sThreadLocal.set(new Looper(quitAllowed)); }
这里通过调用调用prepare()方法,创建了Looper对象,而且sThreadLocal如果没有Looper,则新建Looper进去,如果存在,则抛出异常,而且从判空可以看出一个线程最多只能创建一个Looper对象,验证了很多人说的一个线程一个Looper对象的说法。
上面提到在Looper的构造方法中,会创建MessageQueue对象,我们看一下Looper构造方法:
private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }
没有错,Looper创建的同时会创建MessageQueue,所以很多人说一个Looper对应一个MessageQueue就是从这里来的。Looper跟MessageQueue都创建好了,接下来看如何发送Message消息。
2)handler.sendMessage(message)发送消息到什么地方,内部怎么处理
要想知道发送到哪里,怎么处理,只有一条路,跟到源码中去看:
public final boolean sendMessage(Message msg) { return sendMessageDelayed(msg, 0); }
public final boolean sendMessageDelayed(Message msg, long delayMillis) { if (delayMillis < 0) { delayMillis = 0; } return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis); }
public boolean sendMessageAtTime(Message msg, long uptimeMillis) { MessageQueue queue = mQueue; if (queue == null) { RuntimeException e = new RuntimeException( this + " sendMessageAtTime() called with no mQueue"); Log.w("Looper", e.getMessage(), e); return false; } return enqueueMessage(queue, msg, uptimeMillis); }
前面两个方法就不看了,直接看sendMessageAtTime()方法,sendMessageAtTime()方法中传入两个参数,msg就是我们handler.sendMessage(message)发送的Message对象,而uptimeMillis参数则表示发送消息的时间,它的值等于自系统开机到当前时间的毫秒数再加上延迟时间,如果你调用的不是sendMessageDelayed()方法,则延迟时间就为0。方法最后调用了enqueueMessage()。
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); }
上面方法中,会调用queue.enqueueMessage(msg, uptimeMillis),queue其实就是Looper构造函数中初始化的MessageQueue对象,可以看到,handler把消息发送到MessageQueue中了。
3)MessageQueue对象
接下来我们看queue.enqueueMessage(msg, uptimeMillis);的源码:
boolean enqueueMessage(Message msg, long when) { if (msg.target == null) { throw new IllegalArgumentException("Message must have a target."); } if (msg.isInUse()) { throw new IllegalStateException(msg + " This message is already in use."); } synchronized (this) { if (mQuitting) { IllegalStateException e = new IllegalStateException( msg.target + " sending message to a Handler on a dead thread"); Log.w(TAG, e.getMessage(), e); msg.recycle(); return false; } msg.markInUse(); msg.when = when; Message p = mMessages; boolean needWake; if (p == null || when == 0 || when < p.when) { // New head, wake up the event queue if blocked. msg.next = p; mMessages = msg; needWake = mBlocked; } else { // Inserted within the middle of the queue. Usually we don't have to wake // up the event queue unless there is a barrier at the head of the queue // and the message is the earliest asynchronous message in the queue. needWake = mBlocked && p.target == null && msg.isAsynchronous(); Message prev; for (;;) { prev = p; p = p.next; if (p == null || when < p.when) { break; } if (needWake && p.isAsynchronous()) { needWake = false; } } msg.next = p; // invariant: p == prev.next prev.next = msg; } // We can assume mPtr != 0 because mQuitting is false. if (needWake) { nativeWake(mPtr); } } return true; }
这段代码有点意思,其实就是入队操作,之前一直以为MessageQueue里面有个列表,Message依次保存在里面,其实并不是。MessageQueue借助Message对象(next)成员变量,实现单向链表,并且用一个mMessages对象表示当前待处理的消息。
我们来分析一下上面代码,第二十行,首先Message p = mMessages;把当前待处理的message赋值给p,接下来是一个很长的判断if (p == null || when == 0 || when < p.when),根据判断可以得知,有以下两种情况会执行if里面的语句:1.应用首次调用sendMessage时,当前待处理的消息为null,则p为空,则会执行;2.当前传入msg的when小于当前待处理msg的when,及当前传入的消息要先于当前待处理mMessages得到处理,所以传入的msg赋值为mMessages,而下一个待处理消息才为原先的待处理消息。
if (p == null || when == 0 || when < p.when) { // New head, wake up the event queue if blocked. msg.next = p; mMessages = msg; needWake = mBlocked; }
当执行过多个sendMessage方法时并且消息的时间(when)比当前待处理的消息的时间(when)大,这个时候就会移动链表,根据时间先后,插入到合适的位置,调用如下代码:
Message prev; for (;;) { prev = p; p = p.next; if (p == null || when < p.when) { break; } if (needWake && p.isAsynchronous()) { needWake = false; } } msg.next = p; // invariant: p == prev.next prev.next = msg;
不停的循环,根据when,及发送时间来先后排序,先发送的排在最前面,用message.next来指定下一个Message对象,这样MessageQueue通过时间把多个Message组成一个单向链表。
4)Looper对象,取当前待处理Message。
有进就有出,如何从MessageQueue中获取当前Message进行处理呢,这就要看Looper.loop()方法了。这里可以明白为什么子线程中初始化Handler最后为什么要显示调用Looper.loop()方法了吧,其实相当于启动获取Message方法的循环,主线程中会默认调用。
public static void loop() { final Looper me = myLooper(); if (me == null) { throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); } final MessageQueue queue = me.mQueue; // Make sure the identity of this thread is that of the local process, // and keep track of what that identity token actually is. Binder.clearCallingIdentity(); final long ident = Binder.clearCallingIdentity(); for (;;) { Message msg = queue.next(); // might block if (msg == null) { // No message indicates that the message queue is quitting. return; } // This must be in a local variable, in case a UI event sets the logger Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } msg.target.dispatchMessage(msg); if (logging != null) { logging.println("<<<<< Finished to " + msg.target + " " + msg.callback); } // Make sure that during the course of dispatching the // identity of the thread wasn't corrupted. final long newIdent = Binder.clearCallingIdentity(); if (ident != newIdent) { Log.wtf(TAG, "Thread identity changed from 0x" + Long.toHexString(ident) + " to 0x" + Long.toHexString(newIdent) + " while dispatching to " + msg.target.getClass().getName() + " " + msg.callback + " what=" + msg.what); } msg.recycleUnchecked(); } }
可以看到,第13行依然是一个死循环,不断执行的queue.next()方法,next()方法其实就是做消息出队列操作。获取当前待处理的mMessages对象,然后让下一条消息成为mMessages,其实跟链表操作一样,没有难度。loop()方法的第27行,Message获取到后,则调用msg.target.dispatchMessage(msg)方法,msg是Message对象,target是什么呢?看下Message源码,target其实是发送该Message的Handler对象。
调用Message message = handler1.obtainMessage();的时候,会进行赋值:
public static Message obtain(Handler h) { Message m = obtain(); m.target = h; return m; }
接下来当然就要看一看Handler中dispatchMessage()方法的源码了,如下所示:
public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }
一般情况下,按照我们上面的调用方式,msg.callback,mCallback 都为空,则会直接调用handleMessage(msg)方法,这样终于转到我们的handleMessage方法中来了,在里面去做更新UI的操作。当然有人会问,什么时候msg.callback,mCallback不为空呢?
msg.callback不为空,其实只要看看源码里面,哪些方法可以赋值就可以了:
public static Message obtain(Handler h, Runnable callback) { Message m = obtain(); m.target = h; m.callback = callback; return m; }
下面是我的调用方法:
package com.example.test.myapplication;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;public class MainActivity extends Activity { private Handler handler1 = new Handler(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new Thread(new Runnable() { @Override public void run() { Message message = Message.obtain(handler1, new Runnable() { @Override public void run() { System.out.println("handler2 Thread========="+Thread.currentThread().getName()); } }); message.arg1 = 1; handler1.sendMessage(message); } }).start(); } }
从打印信息可以看到,run方法里面其实也是主线程,这种方式其实很多,下面一一介绍。
4.其他:
上面这个callback的调用方式大家有没有很熟悉呢,其实有几种是大家平时经常使用的:
1.Handler的post()方法
2.View的post()方法
3.Activity的runOnUiThread()方法
这些都可以在子线程中转到主线程,从而去更新UI,至于为什么可以呢,相信很多人不知道。
1)Handler的post()源码
public final boolean post(Runnable r) { return sendMessageDelayed(getPostMessage(r), 0); }
万变不离其宗,其实还是调用sendMessageDelayed方法,而且Runnable还被封装成了Message,后面入链表,出链表过程跟前面讲的都一样。
private static Message getPostMessage(Runnable r) { Message m = Message.obtain(); m.callback = r; return m; }
只是最后的时候,msg.callback != null,他会调用handleCallback(msg);
private static void handleCallback(Message message) { message.callback.run(); }
这样,run方法被调用,是不是很简单。
2)View的post()源码
View类中,post方法:
public boolean post(Runnable action) { final AttachInfo attachInfo = mAttachInfo; if (attachInfo != null) { return attachInfo.mHandler.post(action); } // Assume that post will succeed later ViewRootImpl.getRunQueue().post(action); return true; }
竟然还是mHandler.post(action),原理同上了。
3)Activity的runOnUiThread()源码
public final void runOnUiThread(Runnable action) { if (Thread.currentThread() != mUiThread) { mHandler.post(action); } else { action.run(); } }
如果当前的线程不等于UI线程,仍然执行mHandler.post(action)方法,如果就在主线程,当然直接接口回调,调用run方法就可以了。
5.总结:
所以不管何种子线程转到主线程去刷新UI,背后原理其实都是一样的,搞清楚了一个,都清楚了。希望看到这篇文章后,面试官再问子线程更新主线程的问题的时候,你可以是下面的表情:
原地址http://blog.csdn.net/dfskhgalshgkajghljgh/article/details/52671248