Android多线程分析之三:Handler,Looper的实现
Android多線程分析之三:Handler,Looper的實(shí)現(xiàn)
羅朝輝 (http://blog.csdn.net/kesalin)CC 許可,轉(zhuǎn)載請(qǐng)注明出處
在前文《Android多線程分析之二:Thread的實(shí)現(xiàn)》中已經(jīng)具體分析了Android Thread 是怎樣創(chuàng)建,執(zhí)行以及銷(xiāo)毀的,其重點(diǎn)是對(duì)對(duì)應(yīng) native 方法進(jìn)行分析,今天我將聚焦于 Android Framework 層多線程相關(guān)的類(lèi):Handler, Looper, MessageQueue, Message 以及它們與Thread 之間的關(guān)系。能夠用一個(gè)不太妥當(dāng)?shù)谋扔鱽?lái)形容它們之間的關(guān)聯(lián):假設(shè)把 Thread 比作生產(chǎn)車(chē)間,那么 Looper 就是放在這車(chē)間里的生產(chǎn)線,這條生產(chǎn)線源源不斷地從 MessageQueue 中獲取材料 Messsage,并分發(fā)處理 Message (因?yàn)镸essage 一般是完備的,所以 Looper 大多數(shù)情況下僅僅是調(diào)度讓 Message 的 Handler 去處理 Message)。正是因?yàn)橄㈨氁?Looper 中處理,而 Looper 又需執(zhí)行在 Thread 中,所以不能隨隨便便在非 UI 線程中進(jìn)行 UI 操作。 UI 操作一般會(huì)通過(guò)投遞消息來(lái)實(shí)現(xiàn),僅僅有往正確的 Looper 投遞消息才干得到處理,對(duì)于 UI 來(lái)說(shuō),這個(gè) Looper 一定是執(zhí)行在 UI 線程中。
在編寫(xiě) app 的過(guò)程中,我們經(jīng)常會(huì)這樣來(lái)使用 Handler:
Handler mHandler = new Handler(); mHandler.post(new Runnable(){@Overridepublic void run() {// do somework} });或者如這系列文章第一篇中的演示樣例那樣:
private Handler mHandler= new Handler(){@Overridepublic void handleMessage(Message msg) {Log.i("UI thread", " >> handleMessage()");switch(msg.what){case MSG_LOAD_SUCCESS:Bitmap bitmap = (Bitmap) msg.obj;mImageView.setImageBitmap(bitmap);mProgressBar.setProgress(100);mProgressBar.setMessage("Image downloading success!");mProgressBar.dismiss();break;case MSG_LOAD_FAILURE:mProgressBar.setMessage("Image downloading failure!");mProgressBar.dismiss();break;}}};Message msg = mHandler.obtainMessage(MSG_LOAD_FAILURE, null);mHandler.sendMessage(msg);
首先我們從 Handler 的構(gòu)造函數(shù)開(kāi)始分析:
final MessageQueue mQueue; final Looper mLooper; final Callback mCallback; final boolean mAsynchronous;public Handler(Looper looper, Callback callback, boolean async) {mLooper = looper;mQueue = looper.mQueue;mCallback = callback;mAsynchronous = async;}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 Handler() {this(null, false);}
上面列出了 Handler 的一些成員變量:
mLooper:線程的消息處理循環(huán),注意:并不是每個(gè)線程都有消息處理循環(huán),因此 Framework 中線程能夠分為兩種:有 Looper 的和無(wú) Looper 的。為了方便 app 開(kāi)發(fā),Framework 提供了一個(gè)有 Looper 的 Thread 實(shí)現(xiàn):HandlerThread。在前一篇《Thread的實(shí)現(xiàn)》中也提到了兩種不同 Thread 的 run() 方法的差別。
/*** Handy class for starting a new thread that has a looper. The looper can then be * used to create handler classes. Note that start() must still be called.*/ public class HandlerThread extends Thread {Looper mLooper;/*** Call back method that can be explicitly overridden if needed to execute some* setup before Looper loops.*/protected void onLooperPrepared() {}public void run() {mTid = Process.myTid();Looper.prepare();synchronized (this) {mLooper = Looper.myLooper();notifyAll();}Process.setThreadPriority(mPriority);onLooperPrepared();Looper.loop();mTid = -1;}/*** This method returns the Looper associated with this thread. If this thread not been started* or for any reason is isAlive() returns false, this method will return null. If this thread * has been started, this method will block until the looper has been initialized. * @return The looper.*/public Looper getLooper() {if (!isAlive()) {return null;}// If the thread has been started, wait until the looper has been created.synchronized (this) {while (isAlive() && mLooper == null) {try {wait();} catch (InterruptedException e) {}}}return mLooper;} }
這個(gè) HandlerThread 與 Thread 相比,多了一個(gè)類(lèi)型為 Looper 成員變量?mLooper,它是在 run() 函數(shù)中由 Looper::prepare() 創(chuàng)建的,并保存在 TLS 中:
/** Initialize the current thread as a looper.* This gives you a chance to create handlers that then reference* this looper, before actually starting the loop. Be sure to call* {@link #loop()} after calling this method, and end it by calling* {@link #quit()}.*/public static void prepare() {prepare(true);}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));}
然后通過(guò) Looper::myLooper() 獲取創(chuàng)建的 Looper:
/*** Return the Looper object associated with the current thread. Returns* null if the calling thread is not associated with a Looper.*/public static Looper myLooper() {return sThreadLocal.get();}
最后通過(guò) Looper::Loop() 方法執(zhí)行消息處理循環(huán):從 MessageQueue 中取出消息,并分發(fā)處理該消息,不斷地循環(huán)這個(gè)過(guò)程。這種方法將在后面介紹。
Handler 的成員變量?mQueue 是其成員變量 mLooper 的成員變量,這里僅僅是為了簡(jiǎn)化書(shū)寫(xiě),單獨(dú)拿出來(lái)作為 Handler 的成員變量;成員變量?mCallback 提供了還有一種使用Handler 的簡(jiǎn)便途徑:僅僅需實(shí)現(xiàn)回調(diào)接口?Callback,而無(wú)需子類(lèi)化Handler,以下會(huì)講到的:
/*** Callback interface you can use when instantiating a Handler to avoid* having to implement your own subclass of Handler.*/public interface Callback {public boolean handleMessage(Message msg);}
成員變量?mAsynchronous 是標(biāo)識(shí)是否異步處理消息,假設(shè)是的話,通過(guò)該 Handler obtain 得到的消息都被強(qiáng)制設(shè)置為異步的。
同是否有無(wú) Looper 來(lái)區(qū)分 Thread 一樣,Handler 的構(gòu)造函數(shù)也分為自帶 Looper 和外部 Looper 兩大類(lèi):假設(shè)提供了 Looper,在消息會(huì)在該 Looper 中處理,否則消息就會(huì)在當(dāng)前線程的 Looper 中處理,注意這里要確保當(dāng)前線程一定有 Looper。全部的 UI thread 都是有 Looper 的,因?yàn)?view/widget 的實(shí)現(xiàn)中大量使用了消息,須要 UI thread 提供 Looper 來(lái)處理,能夠參考view.java:
view.javapublic boolean post(Runnable action) {final AttachInfo attachInfo = mAttachInfo;if (attachInfo != null) {return attachInfo.mHandler.post(action);}// Assume that post will succeed laterViewRootImpl.getRunQueue().post(action);return true;}ViewRootImpl.javaprivate void performTraversals() {....// Execute enqueued actions on every traversal in case a detached view enqueued an actiongetRunQueue().executeActions(attachInfo.mHandler);...}static RunQueue getRunQueue() {RunQueue rq = sRunQueues.get();if (rq != null) {return rq;}rq = new RunQueue();sRunQueues.set(rq);return rq;}/*** The run queue is used to enqueue pending work from Views when no Handler is* attached. The work is executed during the next call to performTraversals on* the thread.* @hide*/static final class RunQueue {...void executeActions(Handler handler) {synchronized (mActions) {final ArrayList<HandlerAction> actions = mActions;final int count = actions.size();for (int i = 0; i < count; i++) {final HandlerAction handlerAction = actions.get(i);handler.postDelayed(handlerAction.action, handlerAction.delay);}actions.clear();}}}
從上面的代碼能夠看出,作為全部控件基類(lèi)的 view 提供了 post 方法,用于向 UI Thread 發(fā)送消息,并在 UI Thread 的 Looper 中處理這些消息,而 UI Thread ?一定有 Looper 這是由 ActivityThread 來(lái)保證的:
public final class ActivityThread { ...final Looper mLooper = Looper.myLooper(); }
UI 操作須要向 UI 線程發(fā)送消息并在其 Looper 中處理這些消息。這就是為什么我們不能在非 UI 線程中更新 UI 的原因,在控件在非 UI 線程中構(gòu)造 Handler 時(shí),要么因?yàn)榉?UI 線程沒(méi)有 Looper 使得獲取 myLooper 失敗而拋出 RunTimeException,要么即便提供了 Looper,但這個(gè) Looper 并不是 UI 線程的 Looper 而不能處理控件消息。為此在 ViewRootImpl 中有一個(gè)強(qiáng)制檢測(cè) UI 操作是否是在 UI 線程中處理的方法?checkThread():該方法中的?mThread 是在?ViewRootImpl 的構(gòu)造函數(shù)中賦值的,它就是 UI 線程;該方法中的?Thread.currentThread() 是當(dāng)前進(jìn)行 UI 操作的線程,假設(shè)這個(gè)線程不是非 UI 線程就會(huì)拋出異常CalledFromWrongThreadException。
void checkThread() {if (mThread != Thread.currentThread()) {throw new CalledFromWrongThreadException("Only the original thread that created a view hierarchy can touch its views.");}}
假設(shè)改動(dòng)《使用Thread異步下載圖像》中演示樣例,下載完圖像?bitmap?之后,在 Thread 的 run() 函數(shù)中設(shè)置 ImageView 的圖像為該 bitmap,即會(huì)拋出上面提到的異常:
W/dalvikvm(796): threadid=11: thread exiting with uncaught exception (group=0x40a71930) E/AndroidRuntime(796): FATAL EXCEPTION: Thread-75 E/AndroidRuntime(796): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. E/AndroidRuntime(796): at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:4746) E/AndroidRuntime(796): at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:823) E/AndroidRuntime(796): at android.view.View.requestLayout(View.java:15473) E/AndroidRuntime(796): at android.view.View.requestLayout(View.java:15473) E/AndroidRuntime(796): at android.view.View.requestLayout(View.java:15473) E/AndroidRuntime(796): at android.view.View.requestLayout(View.java:15473) E/AndroidRuntime(796): at android.view.View.requestLayout(View.java:15473) E/AndroidRuntime(796): at android.widget.ImageView.setImageDrawable(ImageView.java:406) E/AndroidRuntime(796): at android.widget.ImageView.setImageBitmap(ImageView.java:421) E/AndroidRuntime(796): at com.example.thread01.MainActivity$2$1.run(MainActivity.java:80)
Handler 的構(gòu)造函數(shù)暫且介紹到這里,接下來(lái)介紹:handleMessage 和?dispatchMessage:
/*** Subclasses must implement this to receive messages.*/public void handleMessage(Message msg) {}/*** Handle system messages here.*/public void dispatchMessage(Message msg) {if (msg.callback != null) {handleCallback(msg);} else {if (mCallback != null) {if (mCallback.handleMessage(msg)) {return;}}handleMessage(msg);}}
前面提到有兩種方式來(lái)設(shè)置處理消息的代碼:一種是設(shè)置 Callback 回調(diào),一種是子類(lèi)化 Handler。而子類(lèi)化?Handler 其子類(lèi)就要實(shí)現(xiàn)?handleMessage 來(lái)處理自己定義的消息,如前面的匿名子類(lèi)演示樣例一樣。dispatchMessage 是在 Looper::Loop() 中被調(diào)用,即它是在線程的消息處理循環(huán)中被調(diào)用,這樣就能讓 Handler 不斷地處理各種消息。在?dispatchMessage 的實(shí)現(xiàn)中能夠看到,假設(shè) Message 有自己的消息處理回調(diào),那么就優(yōu)先調(diào)用消息自己的消息處理回調(diào):
private static void handleCallback(Message message) {message.callback.run();}
否則看Handler 是否有消息處理回調(diào)?mCallback,假設(shè)有且?mCallback 成功處理了這個(gè)消息就返回了,否則就調(diào)用?handleMessage(一般是子類(lèi)的實(shí)現(xiàn)) 來(lái)處理消息。
在分析 Looper::Loop() 這個(gè)關(guān)鍵函數(shù)之前,先來(lái)理一理 Thread,Looper,Handler,MessageQueue 的關(guān)系:Thread 須要有 Looper 才干處理消息(也就是說(shuō) Looper 是執(zhí)行在 Thread 中),這是通過(guò)在自己定義 Thread 的 run() 函數(shù)中調(diào)用 Looper::prepare() 和 Looper::loop() 來(lái)實(shí)現(xiàn),然后在 Looper::loop() 中不斷地從 MessageQueue 獲取由 Handler 投遞到當(dāng)中的 Message,并調(diào)用 Message 的成員變量?Handler 的?dispatchMessage 來(lái)處理消息。
以下先來(lái)看看 Looper 的構(gòu)造函數(shù):
final MessageQueue mQueue;final Thread mThread;volatile boolean mRun;private Looper(boolean quitAllowed) {mQueue = new MessageQueue(quitAllowed);mRun = true;mThread = Thread.currentThread();}
Looper 的構(gòu)造函數(shù)非常easy,創(chuàng)建MessageQueue,保存當(dāng)前線程到 mThread 中。但它是私有的,僅僅能通過(guò)兩個(gè)靜態(tài)函數(shù) prepare()/prepareMainLooper() 來(lái)調(diào)用,前面已經(jīng)介紹了 prepare(),以下來(lái)介紹 prepareMainLooper():
/*** 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();}}
prepareMainLooper 是通過(guò)調(diào)用 prepare 實(shí)現(xiàn)的,只是傳入的參數(shù)為 false,表示?main Looper 不同意中途被中止,創(chuàng)建之后將looper 保持在靜態(tài)變量?sMainLooper 中。整個(gè) Framework 框架僅僅有兩個(gè)地方調(diào)用了?prepareMainLooper 方法:
SystemServer.java 中的 ServerThread,ServerThread 的重要性就不用說(shuō)了,絕大部分 Android Service 都是這個(gè)線程中初始化的。這個(gè)線程是在 Android 啟動(dòng)過(guò)程中的 init2() 方法啟動(dòng)的:
public static final void init2() {Slog.i(TAG, "Entered the Android system server!");Thread thr = new ServerThread();thr.setName("android.server.ServerThread");thr.start();} class ServerThread extends Thread {@Overridepublic void run() {...Looper.prepareMainLooper();...Looper.loop();Slog.d(TAG, "System ServerThread is exiting!");} }
public static void main(String[] args) {....Looper.prepareMainLooper();ActivityThread thread = new ActivityThread();thread.attach(false);if (sMainThreadHandler == null) {sMainThreadHandler = thread.getHandler();}AsyncTask.init();Looper.loop();throw new RuntimeException("Main thread loop unexpectedly exited");}
ActivityThread 的重要性也不言而喻,它是 Activity 的主線程,也就是 UI 線程。注意這里的 AsyncTask.init() ,在后面介紹?AsyncTask 時(shí)會(huì)具體介紹的,這里僅僅提一下:AsyncTask 能夠進(jìn)行 UI 操作正是因?yàn)樵谶@里調(diào)用了 init()。
有了前面的鋪墊,這下我們就能夠來(lái)分析 Looper::Loop() 這個(gè)關(guān)鍵函數(shù)了:
/*** Run the message queue in this thread. Be sure to call* {@link #quit()} to end the 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;...for (;;) {Message msg = queue.next(); // might blockif (msg == null) {// No message indicates that the message queue is quitting.return;}msg.target.dispatchMessage(msg);msg.recycle();}}
loop() 的實(shí)現(xiàn)非常easy,一如前面一再說(shuō)過(guò)的那樣:不斷地從 MessageQueue 中獲取消息,分發(fā)消息,回收消息。從上面的代碼能夠看出,loop() 僅僅是一個(gè)不斷循環(huán)作業(yè)的生產(chǎn)流水線,而 MessageQueue 則為它提供原材料 Message,讓它去分發(fā)處理。至于 Handler 是怎么提交消息到 MessageQueue 中,MessageQueue 又是怎么管理消息的,且待下文分解。
轉(zhuǎn)載于:https://www.cnblogs.com/mengfanrong/p/4216387.html
總結(jié)
以上是生活随笔為你收集整理的Android多线程分析之三:Handler,Looper的实现的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: windows 2008 server
- 下一篇: 日日思君不见君 但愿君心似我心什么意思