Android的消息機(jī)制
一、簡(jiǎn)介
Android的消息機(jī)制主要是指Handler的運(yùn)行機(jī)制,那么什么是Handler的運(yùn)行機(jī)制那?通俗的來(lái)講就是,使用Handler將子線(xiàn)程的Message放入主線(xiàn)程的Messagequeue中,在主線(xiàn)程使用。
二、學(xué)習(xí)內(nèi)容
學(xué)習(xí)Android的消息機(jī)制,我們需要先了解如下內(nèi)容。
- 消息的表示:Message
- 消息隊(duì)列:MessageQueue
- 消息循環(huán),用于循環(huán)取出消息進(jìn)行處理:Looper
- 消息處理,消息循環(huán)從消息隊(duì)列中取出消息后要對(duì)消息進(jìn)行處理:Handler
平常我們接觸的大多是Handler和Message,今天就讓我們來(lái)深入的了解一下他們。
三、代碼詳解
一般而言我們都是這樣使用Handler的
xxHandler.sendEmptyMessage(xxx);
當(dāng)然還有其他表示方法,但我們深入到源代碼中,會(huì)發(fā)現(xiàn),他們最終都調(diào)用了一個(gè)方法
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()方法,但這依然不是結(jié)束,我們可以看到最后一句enqueueMessage(queue, msg, uptimeMillis);按字面意思來(lái)說(shuō)插入一條消息,那么疑問(wèn)來(lái)了,消息插入了哪里。
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; }
進(jìn)入源代碼,我們發(fā)現(xiàn),我們需要了解一個(gè)新類(lèi)Messagequeue。
雖然我們一般把他叫做消息隊(duì)列,但是通過(guò)研究,我們發(fā)下,它實(shí)際上是一種單鏈表的數(shù)據(jù)結(jié)構(gòu),而我們對(duì)它的操作主要是插入和讀取。
看代碼33-44,學(xué)過(guò)數(shù)據(jù)結(jié)構(gòu),我們可以輕松的看出,這是一個(gè)單鏈表的插入末尾的操作。
這樣就明白了,我們send方法實(shí)質(zhì)就是向Messagequeue中插入這么一條消息,那么另一個(gè)問(wèn)題隨之而來(lái),我們?cè)撊绾翁幚磉@條消息。
處理消息我們離不開(kāi)一個(gè)重要的,Looper。那么它在消息機(jī)制中又有什么樣的作用那?
Looper扮演著消息循環(huán)的角色,具體而言它會(huì)不停的從MessageQueue中查看是否有新消息如果有新消息就會(huì)立刻處理,否則就已知阻塞在那里,現(xiàn)在讓我們來(lái)看一下他的代碼實(shí)現(xiàn)。
首先是構(gòu)造方法
private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }
可以發(fā)現(xiàn),它將當(dāng)前線(xiàn)程對(duì)象保存了起來(lái)。我們繼續(xù)
Looper在新線(xiàn)程創(chuàng)建過(guò)程中有兩個(gè)重要的方法looper.prepare() looper.loop
new Thread(){ public void run(){ Looper.prepare(); Handler handler = new Handler(); Looper.loop(); } }.start();
我們先來(lái)看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)); }
咦,我們可以看到這里面又有一個(gè)ThreadLocal類(lèi),我們?cè)谶@簡(jiǎn)單了解一下,他的特性,set(),get()方法。
首先ThreadLocal是一個(gè)線(xiàn)程內(nèi)部的數(shù)據(jù)存儲(chǔ)類(lèi),通過(guò)它可以在指定的線(xiàn)程中存儲(chǔ)數(shù)據(jù),數(shù)據(jù)存儲(chǔ)后,只有在制定線(xiàn)程中可以獲取存儲(chǔ)的數(shù)據(jù),對(duì)于其他線(xiàn)程而言則無(wú)法獲取到數(shù)據(jù)。簡(jiǎn)單的來(lái)說(shuō)。套用一個(gè)列子:
private ThreadLocal<Boolean> mBooleanThreadLocal = new ThreadLocal<Boolean>();// mBooleanThreadLocal.set(true); Log.d(TAH,"Threadmain"+mBooleanThreadLocal.get()); new Thread("Thread#1"){ public void run(){ mBooleanThreadLocal.set(false); Log.d(TAH,"Thread#1"+mBooleanThreadLocal.get()); }; }.start(); new Thread("Thread#2"){ public void run(){ Log.d(TAH,"Thread#2"+mBooleanThreadLocal.get()); }; }.start();
上面的代碼運(yùn)行后,我們會(huì)發(fā)現(xiàn),每一個(gè)線(xiàn)程的值都是不同的,即使他們?cè)L問(wèn)的是同意個(gè)ThreadLocal對(duì)象。
那么我們接下來(lái)會(huì)在之后分析源碼,為什么他會(huì)不一樣?,F(xiàn)在我們跳回prepare()方法那一步,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(); } }
首先loop()方法,獲得這個(gè)線(xiàn)程的Looper,若沒(méi)有拋出異常。再獲得新建的Messagequeue,在這里我們有必要補(bǔ)充一下Messagequeue的next()方法。
Message next() { // Return here if the message loop has already quit and been disposed. // This can happen if the application tries to restart a looper after quit // which is not supported. final long ptr = mPtr; if (ptr == 0) { return null; } int pendingIdleHandlerCount = -1; // -1 only during first iteration int nextPollTimeoutMillis = 0; for (;;) { if (nextPollTimeoutMillis != 0) { Binder.flushPendingCommands(); } nativePollOnce(ptr, nextPollTimeoutMillis); synchronized (this) { // Try to retrieve the next message. Return if found. final long now = SystemClock.uptimeMillis(); Message prevMsg = null; Message msg = mMessages; if (msg != null && msg.target == null) { // Stalled by a barrier. Find the next asynchronous message in the queue. do { prevMsg = msg; msg = msg.next; } while (msg != null && !msg.isAsynchronous()); } if (msg != null) { if (now < msg.when) { // Next message is not ready. Set a timeout to wake up when it is ready. nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE); } else { // Got a message. mBlocked = false; if (prevMsg != null) { prevMsg.next = msg.next; } else { mMessages = msg.next; } msg.next = null; if (DEBUG) Log.v(TAG, "Returning message: " + msg); msg.markInUse(); return msg; } } else { // No more messages. nextPollTimeoutMillis = -1; } // Process the quit message now that all pending messages have been handled. if (mQuitting) { dispose(); return null; } // If first time idle, then get the number of idlers to run. // Idle handles only run if the queue is empty or if the first message // in the queue (possibly a barrier) is due to be handled in the future. if (pendingIdleHandlerCount < 0 && (mMessages == null || now < mMessages.when)) { pendingIdleHandlerCount = mIdleHandlers.size(); } if (pendingIdleHandlerCount <= 0) { // No idle handlers to run. Loop and wait some more. mBlocked = true; continue; } if (mPendingIdleHandlers == null) { mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)]; } mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers); } // Run the idle handlers. // We only ever reach this code block during the first iteration. for (int i = 0; i < pendingIdleHandlerCount; i++) { final IdleHandler idler = mPendingIdleHandlers[i]; mPendingIdleHandlers[i] = null; // release the reference to the handler boolean keep = false; try { keep = idler.queueIdle(); } catch (Throwable t) { Log.wtf(TAG, "IdleHandler threw exception", t); } if (!keep) { synchronized (this) { mIdleHandlers.remove(idler); } } } // Reset the idle handler count to 0 so we do not run them again. pendingIdleHandlerCount = 0; // While calling an idle handler, a new message could have been delivered // so go back and look again for a pending message without waiting. nextPollTimeoutMillis = 0; } }
從24-30我們可以看到,他遍歷了整個(gè)queue找到msg,若是msg為null,我們可以看到50,他把nextPollTimeoutMillis = -1;實(shí)際上是等待enqueueMessage的nativeWake來(lái)喚醒。較深的源碼涉及了native層代碼,有興趣可以研究一下。簡(jiǎn)單來(lái)說(shuō)next()方法,在有消息是會(huì)返回這條消息,若沒(méi)有,則阻塞在這里。
我們回到loop()方法27msg.target.dispatchMessage(msg);我們看代碼
public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }
msg.target實(shí)際上就是發(fā)送這條消息的Handler,我們可以看到它將msg交給dispatchMessage(),最后調(diào)用了我們熟悉的方法handleMessage(msg);
三、總結(jié)
到目前為止,我們了解了android的消息機(jī)制流程,但它實(shí)際上還涉及了深層的native層方法.
以上就是本文的全部?jī)?nèi)容,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,同時(shí)也希望多多支持腳本之家!
- android異步消息機(jī)制 從源碼層面解析(2)
- android異步消息機(jī)制 源碼層面徹底解析(1)
- 代碼分析Android消息機(jī)制
- Android異步消息機(jī)制詳解
- android線(xiàn)程消息機(jī)制之Handler詳解
- android利用消息機(jī)制獲取網(wǎng)絡(luò)圖片
- Android 消息機(jī)制詳解及實(shí)例代碼
- Android消息機(jī)制Handler的工作過(guò)程詳解
- 深入剖析Android消息機(jī)制原理
- Android 消息機(jī)制以及handler的內(nèi)存泄露
- 從源碼角度分析Android的消息機(jī)制
相關(guān)文章
Android中查看USB連接的外接設(shè)備信息的代碼實(shí)例
這篇文章主要介紹了Android中查看USB連接的外接設(shè)備信息的代碼實(shí)例,需要的朋友可以參考下2014-04-04淺析Android中build.gradle的實(shí)用技巧
這篇文章主要介紹了淺析Android中build.gradle的實(shí)用技巧,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-03-03Android組合控件實(shí)現(xiàn)功能強(qiáng)大的自定義控件
這篇文章主要介紹了Android組合控件實(shí)現(xiàn)功能強(qiáng)大的自定義控件的相關(guān)資料,需要的朋友可以參考下2016-05-05Android 使用版本控制工具時(shí)添加忽略文件的方式(詳解)
下面小編就為大家?guī)?lái)一篇Android 使用版本控制工具時(shí)添加忽略文件的方式(詳解)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-01-01Android實(shí)現(xiàn)動(dòng)態(tài)高斯模糊效果
在Android開(kāi)發(fā)中常常會(huì)用到高斯模糊,但有的時(shí)候我們可能會(huì)需要一個(gè)圖片以不同的模糊程度展現(xiàn)出來(lái),那如何實(shí)現(xiàn)呢,一起通過(guò)本文來(lái)學(xué)習(xí)學(xué)習(xí)吧。2016-08-08