1.前言
Handler Message是android中比較常用的異步消息機制,通常我們對UI更新,對異步操作運算,很多時候都採用Handler來實現,現在我們探討一下Handler,Message以及Looper的消息機制。
2.一般使用方法
通常我們使用Handler的一般流程是:
創建Handler對象,並在handleMessage實現消息接受的具體實現;
private final static int MSG_UPDATE = 0x01;
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_UPDATE:
//處理邏輯
break;
}
}
};
創建Message對象,並設置Message屬性;
Message msg = Message.obtain();
msg.what = MSG_UPDATE;
通過Handler的sendMessage方法發送消息對象。
mHandler.sendMessage(msg);
通過在Activity或者其他類裏面創建一個Handler對象後,通過在不同時刻不同需求,通過發消息的形式,對界面進行更新或實現其他的業務邏輯。那Android Framework給開發者提供的這種簡單便利的Handler消息異步機制是怎麼實現的呢?
3.源碼分析
3.1 Handler 部分
在創建Handler對象時候,到底經歷了一個什麼過程呢?
我們結合android-26源碼進行源碼分析。
首先,通過代碼跟蹤,實例化Handler時候,實際上是調用了
public Handler() {
this(null, false);
}
然後實質上是調用了
public Handler(Callback callback, boolean async) {
if (FIND_POTENTIAL_LEAKS) {
final Class<? extends Handler> klass = getClass();
if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
(klass.getModifiers() & Modifier.STATIC) == 0) {
Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
klass.getCanonicalName());
}
}
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
這裏我們也看一下myLooper方法
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
從上面的源碼可以看出,我們在實例化Handler時候,實際上是從sThreadLocal對象中取出Looper。如果sThreadLocal中有Looper存在就返回Looper;若Looper爲空,直接拋出Can’t create handler inside thread that has not called Looper.prepare()的異常。
那爲什麼我們在創建時候沒有報異常,而可以取到Looper對象呢?這是應爲我們的Activity裏面已經調用了Looper.prepareMainLooper();我們可以通過查看ActivityThread的源碼的main入口來看,
public final class ActivityThread {
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
if (activity != null) {
activity.attach(appContext, this, ..., );
public static void main(String[] args) {
// 在這兒調用 Looper.prepareMainLooper, 爲應用的主線程創建Looper
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
Looper.loop();
}
}
這裏的ActivityThread.main方法也是我們通常說的android應用程序的入口。而Activity的生命週期的開始是在
ActivityThread .attach(false)後開始的,所以我們在Activity裏面創建Handler實例時候,就已經有了一個Looper,而且是主線程Looper。通過源碼我們可以很清楚看出。
/**
* Initialize the current thread as a looper, marking it as an
* application's main looper. The main looper for your application
* is created by the Android environment, so you should never need
* to call this function yourself. See also: {@link #prepare()}
*/
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
這裏ActivityThread.main()中調用 Looper.prepareMainLooper, 爲應用的主線程創建Looper。
到這裏Handler的主要源碼就到此爲止,後面有些注意點要補充的。
3.2 Message 部分
Message源碼部分比較簡單,Message類實現了Parcelable接口,可以理解爲比較普通的實體類。
主要屬性有:
public final class Message implements Parcelable {
public int what;
public int arg1;
public int arg2;
public Object obj;
...
long when;
Bundle data;
Handler target;
Runnable callback;
Message next;
}
Message類本身沒有什麼多大探究的,現在我們關係的是Message是怎麼發送出去的?
那麼我們現在要看看Handler的sendMessage方法了。這裏又要到Handler源碼裏面取查看相關的方法實現。重點是消息的發送的實現。
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
接着查看sendMessageDelayed
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
接着sendMessageAtTime
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);
}
從這裏看出,獲取到當前消息隊列queue,然後將msg消息加入到消息隊列queue,這裏的消息隊列其實就是一個單向鏈表。我們看看enqueueMessage方法
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
這裏我們可以清楚看出msg.target就是Handler對象。
此時再看MessageQueue的enqueueMessage方法
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;
}
消息Message通過調用enqueueMessage方法進行入隊加入MessageQueue並且將所有的消息按時間來進行排序。
消息的加入算是明白了,但是消息的是怎麼取出來,然後進行處理的呢?接下來一起看Looper源碼。
3.3 Looper 部分
在上一節分析ActivityThread源碼時,我們很清楚發現,main方法裏面不僅調用了 Looper.prepareMainLooper,而且也調用了Looper.loop方法。查看Loop方法
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
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
final long end;
try {
msg.target.dispatchMessage(msg);
end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (slowDispatchThresholdMs > 0) {
final long time = end - start;
if (time > slowDispatchThresholdMs) {
Slog.w(TAG, "Dispatch took " + time + "ms on "
+ Thread.currentThread().getName() + ", h=" +
msg.target + " cb=" + msg.callback + " msg=" + msg.what);
}
}
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();
}
}
首先我們通過myLoop獲取到當前loop,然後從中拿到MessageQueue實體對象,然後通過for (;;) 循環語句一直循環queue.next()獲取下一個Message,若MessageQueue爲空,則隊列阻塞。
通MessageQueue中拿到Message對象後,通調用 msg.target.dispatchMessage(msg)進行消息分發處理。這裏的msg.target就是Handler本身,前面已經講過了。
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
當msg.callback != null是執行handleCallback;當callback 爲空,調用Handler的handleMessage()方法。這也是在實例化Handler裏面的回調處理handleMessage方法。至此,整個Handler、Message、Looper源碼已經講完了,下一節我們要進行一些補充和歸納。
4.補充與疑問
4.1 Handler.post方法不一定都主線程運行,但是能更新UI
首先我們查看post方法的具體實現
/**
* 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);
}
通過源碼的註釋可以看出,在調用post方法時候,創建的Runnable實例是在所屬的Handler對象線程裏面運行的。如果Handler不是主線程,那麼post後的runnable對象也不在主線程裏面運行。
例如,我們可以這樣做個實驗
public class MainActivity extends AppCompatActivity {
private final static String TAG = MainActivity.class.getSimpleName();
HandlerThread mHandlerThread = new HandlerThread("MyThread");
Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandlerThread.start();
mHandler = new Handler(mHandlerThread.getLooper());
long id = Thread.currentThread().getId();
Log.d(TAG, "Main ThreadName:" + Thread.currentThread().getName() + " ThreadId:" + id);
new Thread(new Runnable() {
@Override
public void run() {
mHandler.post(new Runnable() {
@Override
public void run() {
long id = Thread.currentThread().getId();
Log.d(TAG, "Thread ThreadName:" + Thread.currentThread().getName() + " ThreadId:" + id);
Toast.makeText(MainActivity.this, "nihao", Toast.LENGTH_SHORT).show();
}
});
}
}).start();
}
}
打印結果是:
我們可以很清楚看出,運行在post裏面的線程的ThreadId並不是主線程Id=1,也就是說,此時的post運行不在主線程裏面。但是Toast能正常顯示提示,沒有報異常。
那爲什麼我們經常在Activity裏面取調用post更新UI不報錯了?
這跟我們在子線程中更新UI的方法一樣了,如下面我們常在子線程中更新UI的代碼
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
Toast.makeText(MainActivity.this, "nihao", Toast.LENGTH_SHORT).show();
Looper.loop();
}
}).start();
4.2 ThreadLocal
在一個android應用中編程,我們通常需要很多handler消息機制來實現各種功能,但是我們怎樣保證handler對應的looper的唯一和handler消息的多線程問題了,這裏就引出了ThreadLocal。
ThreadLocal使用場合主要解決多線程中數據因併發產生不一致的問題。ThreadLocal以空間換時間,爲每個線程的中併發訪問的數據提供一個副本,通過訪問副本來運行業務,這樣的結果是耗費了內存,但大大減少了線程同步所帶來的線程消耗,也減少了線程併發控制的複雜度。
那麼我們切換到Looper源碼,很容易看到
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
實際上,我們每個線程的Looper都存放到ThreadLocal裏面,可以把ThreadLocal看做是一個容器,容器裏面存放着屬於當前線程的變量。此時這裏是存放當前線程的Looper變量。通過ThreadLocal,每個線程的Looper相互不影響而分別工作的。
關於ThreadLocal的詳細,可以參考:http://blog.csdn.net/lufeng20/article/details/24314381
5.總結
看完了Handler、Message、Looper的分析後,我們總結一下三者的工作流程:
如圖(ps:網上盜用圖片),當我們創建好Handler後,通過Handler.sendMessage方法發送消息,此時將消息加載到MessageQueue,每次將新消息加入消息隊列時候,消息隊列根據時間進行排序,然後通過調用Looper.loop,裏面for循環一直輪訓消息隊列的消息,如果沒有消息,循環阻塞;如果有消息,取出消息後,進行dispatchMessage處理,調用Handler裏面的runnable或者handleMessage方法進行UI或者邏輯處理,到達異步消息處理機制。。。