在安卓程序啓動時,會默認在主線程中 運行程序,那若是執行一些耗時的操做則UI就會處於阻塞狀態,出現界面卡頓的現象,再者用戶的多種操做,系統是如何作到一一處理的,系統又是如何管理這些任務的,答案這就是今天的主題Android的消息機制;bash
對於Handler的使用方法此處不作介紹,在使用是隻要注意避免內存泄漏需建立靜態Handler,此處從執行過程和原理的角度簡單分析Handler的源碼,首先你們都知道在主線程中能夠直接使用Handler,而在子線程中不能夠,有沒有想過爲何呢?如今就先看看主線程究竟有什麼不一樣吧,從頭看安卓的入口方法ActivityThread.main()async
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
...
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"));
}
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
複製代碼
Handler與消息隊列關聯,而消息隊列被封裝在Looper中,每一個Looper關聯一個線程,因此Handler的消息大體爲handler做爲一個消息處理器,將消息傳遞到消息隊列中,線程中的Looper逐個取出消息並執行,此處的線程即爲UI線程,ide
public Handler(Callback callback, boolean async) {
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;
}
複製代碼
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}複製代碼
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));
}複製代碼
到這裏咱們介紹了Handler 和 Looper的建立,以及各自對線程的關聯,下面查看如何啓動消息循環獲取任務並執行,在入口方法的最後調用了Loop.loop()方法,下面查看Looper.loop()方法:oop
public static void loop() {
final Looper me = myLooper();
final MessageQueue queue = me.mQueue;
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
return;
}
...
msg.target.dispatchMessage(msg);
msg.recycleUnchecked();
}複製代碼
Handler target;
Runnable callback;
Message next;複製代碼
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
private static void handleCallback(Message message) {
message.callback.run();
}複製代碼
總結一下:looper從MessageQuene中依次取出Message,而後調用Msg綁定的Handler的dispatchMessage(msg)處理,dispatchMessage()中依次判斷執行:源碼分析
到此Android中Handler的消息處理,從建立Handler、Looper和MessageQueue到消息的傳遞和事件的處理都介紹完了,下面咱們看看使用時如何發送消息到MessageQueue以及上述的callback、mCallBack什麼狀況下爲空?post
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;
return enqueueMessage(queue, msg, uptimeMillis);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this; // 此處設置target爲Handler對象
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}複製代碼
上面的執行過程代碼從上倒下一目瞭然,在enqueueMessage()中設置了Message.target即爲調用方法的Handler,因此在調用dispatchMessage()時,會調用Handler的handleMessage()處理ui
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r; // 設置Message的callback爲r
return m;
}複製代碼
Handler消息機制的原理和過程介紹完畢了,此時知道爲何不能在子線程建立handler嗎?拋出的異常在上述代碼中也出現了this
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}複製代碼
當Looper.myLooper()取出爲空時拋出異常,而myLooper()中時從sThreadLocal.get()中獲取,即此時sThreadLocal中沒有設置Looper對象,因此也就沒有後面的隊列等操做,從上面知道建立並設置Looper對象是在prepare()方法中,因此要在子線程中使用Handler要先調用Looper.prepare()建立Looper對象,後調用Looper.loop()開啓消息循環。spa