Android Handler的原理
簡(jiǎn)介
在 Android 中,只有主線程才能操作 UI,但是主線程不能進(jìn)行耗時(shí)操作,否則會(huì)阻塞線程,產(chǎn)生 ANR 異常,所以常常把耗時(shí)操作放到其它子線程進(jìn)行。如果在子線程中需要更新 UI,一般是通過 Handler 發(fā)送消息,主線程接受消息并且進(jìn)行相應(yīng)的邏輯處理。除了直接使用 Handler,還可以通過 View 的 post 方法以及 Activity 的 runOnUiThread 方法來更新 UI,它們內(nèi)部也是利用了 Handler 。在上一篇文章 Android AsyncTask源碼分析 中也講到,其內(nèi)部使用了 Handler 把任務(wù)的處理結(jié)果傳回 UI 線程。
本文深入分析 Android 的消息處理機(jī)制,了解 Handler 的工作原理。
Handler
先通過一個(gè)例子看一下 Handler 的用法。
public class MainActivity extends AppCompatActivity {private static final int MESSAGE_TEXT_VIEW = 0;private TextView mTextView;private Handler mHandler = new Handler() {@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case MESSAGE_TEXT_VIEW:mTextView.setText("UI成功更新");default:super.handleMessage(msg);}}};@Overrideprotected 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() {@Overridepublic void run() {try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}mHandler.obtainMessage(MESSAGE_TEXT_VIEW).sendToTarget();}}).start();} }上面的代碼先是新建了一個(gè) Handler的實(shí)例,并且重寫了 handleMessage 方法,在這個(gè)方法里,便是根據(jù)接受到的消息的類型進(jìn)行相應(yīng)的 UI 更新。那么看一下 Handler的構(gòu)造方法的源碼:
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; }在構(gòu)造方法中,通過調(diào)用 Looper.myLooper() 獲得了 Looper 對(duì)象。如果 mLooper 為空,那么會(huì)拋出異常:"Can't create handler inside thread that has not called Looper.prepare()",意思是:不能在未調(diào)用 Looper.prepare() 的線程創(chuàng)建 handler。上面的例子并沒有調(diào)用這個(gè)方法,但是卻沒有拋出異常。其實(shí)是因?yàn)橹骶€程在啟動(dòng)的時(shí)候已經(jīng)幫我們調(diào)用過了,所以可以直接創(chuàng)建 Handler 。如果是在其它子線程,直接創(chuàng)建 Handler 是會(huì)導(dǎo)致應(yīng)用崩潰的。
在得到 Handler 之后,又獲取了它的內(nèi)部變量 mQueue, 這是 MessageQueue 對(duì)象,也就是消息隊(duì)列,用于保存 Handler 發(fā)送的消息。
到此,Android 消息機(jī)制的三個(gè)重要角色全部出現(xiàn)了,分別是 Handler 、Looper 以及 MessageQueue。 一般在代碼我們接觸比較多的是 Handler ,但 Looper 與 MessageQueue 卻是 Handler 運(yùn)行時(shí)不可或缺的。
Looper
上一節(jié)分析了 Handler 的構(gòu)造,其中調(diào)用了 Looper.myLooper() 方法,下面是它的源碼:
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();public static @Nullable Looper myLooper() {return sThreadLocal.get(); }這個(gè)方法的代碼很簡(jiǎn)單,就是從 sThreadLocal 中獲取 Looper 對(duì)象。sThreadLocal 是 ThreadLocal 對(duì)象,這說明 Looper 是線程獨(dú)立的。
在 Handler 的構(gòu)造中,從拋出的異??芍?#xff0c;每個(gè)線程想要獲得 Looper 需要調(diào)用 prepare() 方法,繼續(xù)看它的代碼:
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)); }同樣很簡(jiǎn)單,就是給 sThreadLocal 設(shè)置一個(gè) Looper。不過需要注意的是如果 sThreadLocal 已經(jīng)設(shè)置過了,那么會(huì)拋出異常,也就是說一個(gè)線程只會(huì)有一個(gè) Looper。創(chuàng)建 Looper 的時(shí)候,內(nèi)部會(huì)創(chuàng)建一個(gè)消息隊(duì)列:
private Looper(boolean quitAllowed) {mQueue = new MessageQueue(quitAllowed);mThread = Thread.currentThread(); }現(xiàn)在的問題是, Looper看上去很重要的樣子,它到底是干嘛的?
回答: Looper 開啟消息循環(huán)系統(tǒng),不斷從消息隊(duì)列 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();//無限循環(huán)for (;;) {Message msg = queue.next(); // might blockif (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 loggerPrinter 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();} }這個(gè)方法的代碼有點(diǎn)長(zhǎng),不去追究細(xì)節(jié),只看整體邏輯??梢钥闯?#xff0c;在這個(gè)方法內(nèi)部有個(gè)死循環(huán),里面通過 MessageQueue 的 next() 方法獲取下一條消息,沒有獲取到會(huì)阻塞。如果成功獲取新消息,便調(diào)用 msg.target.dispatchMessage(msg),msg.target是 Handler 對(duì)象(下一節(jié)會(huì)看到),dispatchMessage 則是分發(fā)消息(此時(shí)已經(jīng)運(yùn)行在 UI 線程),下面分析消息的發(fā)送及處理流程。
消息發(fā)送與處理
在子線程發(fā)送消息時(shí),是調(diào)用一系列的 sendMessage、sendMessageDelayed 以及 sendMessageAtTime 等方法,最終會(huì)輾轉(zhuǎn)調(diào)用 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); }這個(gè)方法就是調(diào)用 enqueueMessage 在消息隊(duì)列中插入一條消息,在 enqueueMessage總中,會(huì)把 msg.target 設(shè)置為當(dāng)前的 Handler 對(duì)象。
消息插入消息隊(duì)列后, Looper 負(fù)責(zé)從隊(duì)列中取出,然后調(diào)用 Handler 的 dispatchMessage 方法。接下來看看這個(gè)方法是怎么處理消息的:
public void dispatchMessage(Message msg) {if (msg.callback != null) {handleCallback(msg);} else {if (mCallback != null) {if (mCallback.handleMessage(msg)) {return;}}handleMessage(msg);} }首先,如果消息的 callback 不是空,便調(diào)用 handleCallback 處理。否則判斷 Handler 的 mCallback 是否為空,不為空則調(diào)用它的 handleMessage方法。如果仍然為空,才調(diào)用 Handler 自身的 handleMessage,也就是我們創(chuàng)建 Handler 時(shí)重寫的方法。
如果發(fā)送消息時(shí)調(diào)用 Handler 的 post(Runnable r)方法,會(huì)把 Runnable封裝到消息對(duì)象的 callback,然后調(diào)用 sendMessageDelayed,相關(guān)代碼如下:
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; }此時(shí)在 dispatchMessage中便會(huì)調(diào)用 handleCallback進(jìn)行處理:
private static void handleCallback(Message message) {message.callback.run(); }可以看到是直接調(diào)用了 run 方法處理消息。
如果在創(chuàng)建 Handler時(shí),直接提供一個(gè) Callback 對(duì)象,消息就交給這個(gè)對(duì)象的 handleMessage 方法處理。Callback 是 Handler 內(nèi)部的一個(gè)接口:
public interface Callback {public boolean handleMessage(Message msg); }以上便是消息發(fā)送與處理的流程,發(fā)送時(shí)是在子線程,但處理時(shí) dispatchMessage 方法運(yùn)行在主線程。
總結(jié)
至此,Android消息處理機(jī)制的原理就分析結(jié)束了。現(xiàn)在可以知道,消息處理是通過 Handler 、Looper 以及 MessageQueue共同完成。 Handler 負(fù)責(zé)發(fā)送以及處理消息,Looper 創(chuàng)建消息隊(duì)列并不斷從隊(duì)列中取出消息交給 Handler, MessageQueue 則用于保存消息。
如果我的文章對(duì)您有幫助,不妨點(diǎn)個(gè)贊鼓勵(lì)一下(^_^)
總結(jié)
以上是生活随笔為你收集整理的Android Handler的原理的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 今天介绍一款强大的服务器开发工具(JRe
- 下一篇: 数据结构--二叉树(1)