編輯:Android資訊
在 Android 中,只有主線程才能操作 UI,但是主線程不能進行耗時操作,否則會阻塞線程,產生 ANR 異常,所以常常把耗時操作放到其它子線程進行。如果在子線程中需要更新 UI,一般是通過 Handler 發送消息,主線程接受消息並且進行相應的邏輯處理。除了直接使用 Handler,還可以通過 View 的 post 方法以及 Activity 的 runOnUiThread 方法來更新 UI,它們內部也是利用了 Handler。在上一篇文章 Android AsyncTask源碼分析 中也講到,其內部使用了 Handler 把任務的處理結果傳回 UI 線程。
本文深入分析 Android 的消息處理機制,了解 Handler 的工作原理。
先通過一個例子看一下 Handler 的用法。
public class MainActivity extends AppCompatActivity {
private static final int MESSAGE_TEXT_VIEW = 0;
private TextView mTextView;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_TEXT_VIEW:
mTextView.setText("UI成功更新");
default:
super.handleMessage(msg);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mTextView = (TextView) findViewById(R.id.text_view);
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
mHandler.obtainMessage(MESSAGE_TEXT_VIEW).sendToTarget();
}
}).start();
}
}
上面的代碼先是新建了一個 Handler的實例,並且重寫了 handleMessage 方法,在這個方法裡,便是根據接受到的消息的類型進行相應的 UI 更新。那麼看一下 Handler的構造方法的源碼:
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;
}
在構造方法中,通過調用 Looper.myLooper() 獲得了 Looper 對象。如果 mLooper 為空,那麼會拋出異常:”Can’t create handler inside thread that has not called Looper.prepare()”,意思是:不能在未調用 Looper.prepare() 的線程創建 handler。上面的例子並沒有調用這個方法,但是卻沒有拋出異常。其實是因為主線程在啟動的時候已經幫我們調用過了,所以可以直接創建 Handler 。如果是在其它子線程,直接創建 Handler 是會導致應用崩潰的。
在得到 Handler 之後,又獲取了它的內部變量 mQueue, 這是 MessageQueue 對象,也就是消息隊列,用於保存 Handler 發送的消息。
到此,Android 消息機制的三個重要角色全部出現了,分別是 Handler 、Looper 以及 MessageQueue。 一般在代碼我們接觸比較多的是 Handler ,但 Looper 與 MessageQueue 卻是 Handler 運行時不可或缺的。
上一節分析了 Handler 的構造,其中調用了 Looper.myLooper() 方法,下面是它的源碼:
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
這個方法的代碼很簡單,就是從 sThreadLocal 中獲取 Looper 對象。sThreadLocal 是 ThreadLocal 對象,這說明 Looper 是線程獨立的。
在 Handler 的構造中,從拋出的異常可知,每個線程想要獲得 Looper 需要調用 prepare() 方法,繼續看它的代碼:
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));
}
同樣很簡單,就是給 sThreadLocal 設置一個 Looper。不過需要注意的是如果 sThreadLocal 已經設置過了,那麼會拋出異常,也就是說一個線程只會有一個 Looper。創建 Looper 的時候,內部會創建一個消息隊列:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
現在的問題是, Looper看上去很重要的樣子,它到底是干嘛的?
回答: Looper 開啟消息循環系統,不斷從消息隊列 MessageQueue 取出消息交由 Handler 處理。
為什麼這樣說呢,看一下 Looper 的 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
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();
}
}
這個方法的代碼有點長,不去追究細節,只看整體邏輯。可以看出,在這個方法內部有個死循環,裡面通過 MessageQueue 的next() 方法獲取下一條消息,沒有獲取到會阻塞。如果成功獲取新消息,便調用msg.target.dispatchMessage(msg),msg.target是 Handler 對象(下一節會看到),dispatchMessage 則是分發消息(此時已經運行在 UI 線程),下面分析消息的發送及處理流程。
在子線程發送消息時,是調用一系列的 sendMessage、sendMessageDelayed 以及 sendMessageAtTime 等方法,最終會輾轉調用sendMessageAtTime(Message msg, long uptimeMillis),代碼如下:
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);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
這個方法就是調用 enqueueMessage 在消息隊列中插入一條消息,在 enqueueMessage總中,會把 msg.target 設置為當前的Handler 對象。
消息插入消息隊列後, Looper 負責從隊列中取出,然後調用 Handler 的 dispatchMessage 方法。接下來看看這個方法是怎麼處理消息的:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
首先,如果消息的 callback 不是空,便調用 handleCallback 處理。否則判斷 Handler 的 mCallback 是否為空,不為空則調用它的 handleMessage方法。如果仍然為空,才調用 Handler 自身的 handleMessage,也就是我們創建 Handler 時重寫的方法。
如果發送消息時調用 Handler 的 post(Runnable r)方法,會把 Runnable封裝到消息對象的 callback,然後調用sendMessageDelayed,相關代碼如下:
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
此時在 dispatchMessage中便會調用 handleCallback進行處理:
private static void handleCallback(Message message) {
message.callback.run();
}
可以看到是直接調用了 run 方法處理消息。
如果在創建 Handler時,直接提供一個 Callback 對象,消息就交給這個對象的 handleMessage 方法處理。Callback 是 Handler內部的一個接口:
public interface Callback {
public boolean handleMessage(Message msg);
}
以上便是消息發送與處理的流程,發送時是在子線程,但處理時 dispatchMessage 方法運行在主線程。
至此,Android消息處理機制的原理就分析結束了。現在可以知道,消息處理是通過 Handler 、Looper 以及 MessageQueue共同完成。 Handler 負責發送以及處理消息,Looper 創建消息隊列並不斷從隊列中取出消息交給 Handler, MessageQueue 則用於保存消息。
Android GUI之View布局
在清楚了View繪制機制中的第一步測量之後,我們繼續來了解分析View繪制的第二個過程,那就是布局定位。繼續跟蹤分析源碼,根據之前的流程分析我們知道View的繪制
使用 Unity 開發 Android 游戲時如何追蹤性能問題
前言 兩周前我開始用 Unity 開發一個叫 SkyBlocks 的 Android 游戲。游戲已經在 Google Play 上架了,如果你有時間可以下載來玩一
Android布局優化之ViewStub、include、merge使用與源碼分析
在開發中UI布局是我們都會遇到的問題,隨著UI越來越多,布局的重復性、復雜度也會隨之增長。Android官方給了幾個優化的方法,但是網絡上的資料基本上都是對官方資
Android依賴注入之BufferKnife 8.0注解使用
前言: App項目開發大部分時候還是以UI頁面為主,這時我們需要調用大量的findViewById以及setOnClickListener等代碼,控件的少的時候我