青青草原综合久久大伊人导航_色综合久久天天综合_日日噜噜夜夜狠狠久久丁香五月_热久久这里只有精品

羅朝輝(飄飄白云)

關注嵌入式操作系統,移動平臺,圖形開發。-->加微博 ^_^

  C++博客 :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理 ::
  85 隨筆 :: 0 文章 :: 169 評論 :: 0 Trackbacks
Android多線程分析之三:Handler,Looper的實現

羅朝輝 (http://m.shnenglu.com/kesalin/)

本文遵循“署名-非商業用途-保持一致”創作公用協議

在前文《
Android多線程分析之二:Thread的實現》中已經詳細分析了Android Thread 是如何創建,運行以及銷毀的,其重點是對相應 native 方法進行分析,今天我將聚焦于 Android Framework 層多線程相關的類:Handler, Looper, MessageQueue, Message 以及它們與Thread 之間的關系。可以用一個不太妥當的比喻來形容它們之間的關聯:如果把 Thread 比作生產車間,那么 Looper 就是放在這車間里的生產線,這條生產線源源不斷地從 MessageQueue 中獲取材料 Messsage,并分發處理 Message (由于Message 通常是完備的,所以 Looper 大多數情況下只是調度讓 Message 的 Handler 去處理 Message)。正是因為消息需要在 Looper 中處理,而 Looper 又需運行在 Thread 中,所以不能隨隨便便在非 UI 線程中進行 UI 操作。 UI 操作通常會通過投遞消息來實現,只有往正確的 Looper 投遞消息才能得到處理,對于 UI 來說,這個 Looper 一定是運行在 UI 線程中。

在編寫 app 的過程中,我們常常會這樣來使用 Handler:
Handler mHandler = new Handler();
mHandler.post(new Runnable(){
    @Override
    public void run() {
        // do somework
    }
});

或者如這系列文章第一篇中的示例那樣: 
    private Handler mHandler= new Handler(){
        @Override
        public 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 的 post/sendMessage 背后到底發生了什么事情呢?下面就來解開這個謎團。

首先我們從 Handler 的構造函數開始分析:
    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(nullfalse);
    }

上面列出了 Handler 的一些成員變量:

mLooper:線程的消息處理循環,注意:并非每一個線程都有消息處理循環,因此 Framework 中線程可以分為兩種:有 Looper 的和無 Looper 的。為了方便 app 開發,Framework 提供了一個有 Looper 的 Thread 實現:HandlerThread。在前一篇《Thread的實現》中也提到了兩種不同 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;
    }
}

這個 HandlerThread 與 Thread 相比,多了一個類型為 Looper 成員變量 mLooper,它是在 run() 函數中由 Looper::prepare() 創建的,并保存在 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));
    }

然后通過 Looper::myLooper() 獲取創建的 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();
    }

最后通過 Looper::Loop() 方法運行消息處理循環:從 MessageQueue 中取出消息,并分發處理該消息,不斷地循環這個過程。這個方法將在后面介紹。

Handler 的成員變量 mQueue 是其成員變量 mLooper 的成員變量,這里只是為了簡化書寫,單獨拿出來作為 Handler 的成員變量;成員變量 mCallback 提供了另一種使用Handler 的簡便途徑:只需實現回調接口 Callback,而無需子類化Handler,下面會講到的:
    /**
     * 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 是標識是否異步處理消息,如果是的話,通過該 Handler obtain 得到的消息都被強制設置為異步的。

同是否有無 Looper 來區分 Thread 一樣,Handler 的構造函數也分為自帶 Looper 和外部 Looper 兩大類:如果提供了 Looper,在消息會在該 Looper 中處理,否則消息就會在當前線程的 Looper 中處理,注意這里要確保當前線程一定有 Looper。所有的 UI thread 都是有 Looper 的,因為 view/widget 的實現中大量使用了消息,需要 UI thread 提供 Looper 來處理,可以參考view.java:

view.java

    public boolean post(Runnable action) {
        final AttachInfo attachInfo = mAttachInfo;
        if (attachInfo != null) {
            return attachInfo.mHandler.post(action);
        }
        // Assume that post will succeed later
        ViewRootImpl.getRunQueue().post(action);
        return true;
    }

ViewRootImpl.java

    private void performTraversals() {
        .
        // Execute enqueued actions on every traversal in case a detached view enqueued an action
        getRunQueue().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();
            }
        }
    }

從上面的代碼可以看出,作為所有控件基類的 view 提供了 post 方法,用于向 UI Thread 發送消息,并在 UI Thread 的 Looper 中處理這些消息,而 UI Thread  一定有 Looper 這是由 ActivityThread 來保證的:
public final class ActivityThread {

    final Looper mLooper = Looper.myLooper();
}

UI 操作需要向 UI 線程發送消息并在其 Looper 中處理這些消息。這就是為什么我們不能在非 UI 線程中更新 UI 的原因,在控件在非 UI 線程中構造 Handler 時,要么由于非 UI 線程沒有 Looper 使得獲取 myLooper 失敗而拋出 RunTimeException,要么即便提供了 Looper,但這個 Looper 并非 UI 線程的 Looper 而不能處理控件消息。為此在 ViewRootImpl 中有一個強制檢測 UI 操作是否是在 UI 線程中處理的方法 checkThread():該方法中的 mThread 是在 ViewRootImpl 的構造函數中賦值的,它就是 UI 線程;該方法中的 Thread.currentThread() 是當前進行 UI 操作的線程,如果這個線程不是非 UI 線程就會拋出異常CalledFromWrongThreadException。
    void checkThread() {
        if (mThread != Thread.currentThread()) {
            throw new CalledFromWrongThreadException(
                    "Only the original thread that created a view hierarchy can touch its views.");
        }
    }

如果修改《使用Thread異步下載圖像》中示例,下載完圖像 bitmap 之后,在 Thread 的 run() 函數中設置 ImageView 的圖像為該 bitmap,即會拋出上面提到的異常:
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 的構造函數暫且介紹到這里,接下來介紹: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);
        }
    }

前面提到有兩種方式來設置處理消息的代碼:一種是設置 Callback 回調,一種是子類化 Handler。而子類化 Handler 其子類就要實現 handleMessage 來處理自定義的消息,如前面的匿名子類示例一樣。dispatchMessage 是在 Looper::Loop() 中被調用,即它是在線程的消息處理循環中被調用,這樣就能讓 Handler 不斷地處理各種消息。在 dispatchMessage 的實現中可以看到,如果 Message 有自己的消息處理回調,那么就優先調用消息自己的消息處理回調:
    private static void handleCallback(Message message) {
        message.callback.run();
    }

否則看Handler 是否有消息處理回調 mCallback,如果有且 mCallback 成功處理了這個消息就返回了,否則就調用 handleMessage(通常是子類的實現) 來處理消息。

在分析 Looper::Loop() 這個關鍵函數之前,先來理一理 Thread,Looper,Handler,MessageQueue 的關系:Thread 需要有 Looper 才能處理消息(也就是說 Looper 是運行在 Thread 中),這是通過在自定義 Thread 的 run() 函數中調用 Looper::prepare() 和 Looper::loop() 來實現,然后在 Looper::loop() 中不斷地從 MessageQueue 獲取由 Handler 投遞到其中的 Message,并調用 Message 的成員變量 Handler 的 dispatchMessage 來處理消息。

下面先來看看 Looper 的構造函數:
    final MessageQueue mQueue;
    final Thread mThread;
    volatile boolean mRun;

    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mRun = true;
        mThread = Thread.currentThread();
    }

Looper 的構造函數很簡單,創建MessageQueue,保存當前線程到 mThread 中。但它是私有的,只能通過兩個靜態函數 prepare()/prepareMainLooper() 來調用,前面已經介紹了 prepare(),下面來介紹 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 是通過調用 prepare 實現的,不過傳入的參數為 false,表示 main Looper 不允許中途被中止,創建之后將looper 保持在靜態變量 sMainLooper 中。整個 Framework 框架只有兩個地方調用了 prepareMainLooper 方法:

第一處是在 SystemServer.java 中的 ServerThread,ServerThread 的重要性就不用說了,絕大部分 Android Service 都是這個線程中初始化的。這個線程是在 Android 啟動過程中的 init2() 方法啟動的:
    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 {
    @Override
    public void run() {
        
        Looper.prepareMainLooper();
        
        Looper.loop();
        Slog.d(TAG, "System ServerThread is exiting!");
    }
}

第二處是在 ActivityThread.java 的 main() 方法中:
    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 時會詳細介紹的,這里只提一下:AsyncTask 能夠進行 UI 操作正是由于在這里調用了 init()。

有了前面的鋪墊,這下我們就可以來分析 Looper::Loop() 這個關鍵函數了:
   /**
     * 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 block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

            msg.target.dispatchMessage(msg);

            msg.recycle();
        }
    }

loop() 的實現非常簡單,一如前面一再說過的那樣:不斷地從 MessageQueue 中獲取消息,分發消息,回收消息。從上面的代碼可以看出,loop() 僅僅是一個不斷循環作業的生產流水線,而 MessageQueue 則為它提供原材料 Message,讓它去分發處理。至于 Handler 是怎么提交消息到 MessageQueue 中,MessageQueue 又是怎么管理消息的,且待下文分解。
posted on 2014-07-12 11:00 羅朝輝 閱讀(3017) 評論(0)  編輯 收藏 引用 所屬分類: 移動開發
青青草原综合久久大伊人导航_色综合久久天天综合_日日噜噜夜夜狠狠久久丁香五月_热久久这里只有精品
  • <ins id="pjuwb"></ins>
    <blockquote id="pjuwb"><pre id="pjuwb"></pre></blockquote>
    <noscript id="pjuwb"></noscript>
          <sup id="pjuwb"><pre id="pjuwb"></pre></sup>
            <dd id="pjuwb"></dd>
            <abbr id="pjuwb"></abbr>
            久久精品国产v日韩v亚洲 | 久久久天天操| 国产亚洲成精品久久| 久久成人精品| 久久九九热re6这里有精品| 国产综合久久久久久| 久久一区亚洲| 欧美粗暴jizz性欧美20| 一区二区不卡在线视频 午夜欧美不卡'| 91久久国产综合久久蜜月精品 | 亚洲视频在线观看视频| 国产精品亚洲综合色区韩国| 久久成人人人人精品欧| 久久久欧美精品sm网站| 亚洲精品在线看| 亚洲永久在线观看| 一区二区三区在线高清| 亚洲欧洲一区二区天堂久久| 国产精品久久999| 免费观看成人网| 欧美日韩综合网| 鲁大师成人一区二区三区| 欧美国产日本| 久久精品99无色码中文字幕 | 亚洲国产精品一区制服丝袜 | 久久精品日产第一区二区三区| 在线国产精品一区| 99热免费精品| 亚洲高清网站| 亚洲免费中文字幕| 亚洲精品久久视频| 午夜精品免费| 一本色道久久综合精品竹菊| 久久av一区二区三区亚洲| 日韩一区二区免费看| 欧美一区二区私人影院日本 | 欧美在线观看天堂一区二区三区| 久久经典综合| 亚洲欧美日韩精品久久久久| 免费亚洲电影| 久久亚洲国产精品日日av夜夜| 欧美日韩精品是欧美日韩精品| 裸体素人女欧美日韩| 国产精品极品美女粉嫩高清在线| 欧美高清视频www夜色资源网| 国产精品亚洲精品| 日韩亚洲欧美一区| 亚洲毛片网站| 欧美aⅴ99久久黑人专区| 欧美在线视频在线播放完整版免费观看| 欧美精品一区二区三区在线播放| 老鸭窝91久久精品色噜噜导演| 国产精品美女在线| 一区二区电影免费观看| 制服丝袜亚洲播放| 欧美极品一区| 91久久精品国产91久久性色tv | 在线欧美不卡| 欧美一区二视频| 亚洲愉拍自拍另类高清精品| 欧美国产日本| 亚洲伦理一区| 在线视频亚洲欧美| 欧美日韩蜜桃| 一本色道久久综合亚洲精品小说| 99热免费精品在线观看| 午夜欧美电影在线观看| 欧美黄色网络| 亚洲欧洲综合另类在线| 日韩一级免费| 欧美日本视频在线| 日韩一级黄色片| 午夜精品偷拍| 国产一区 二区 三区一级| 欧美一级黄色网| 农村妇女精品| 亚洲精品免费一区二区三区| 欧美激情女人20p| 一区二区不卡在线视频 午夜欧美不卡'| 99在线热播精品免费99热| 欧美黄色aa电影| 在线一区视频| 久久精品成人一区二区三区 | 免费亚洲电影在线观看| 亚洲高清不卡在线观看| 一本在线高清不卡dvd| 国产精品国产三级国产专播精品人| 亚洲天堂第二页| 久久美女艺术照精彩视频福利播放| 韩国一区二区在线观看| 免费91麻豆精品国产自产在线观看| 欧美黄色视屏| 亚洲综合国产精品| 激情一区二区| 欧美人在线视频| 亚洲欧美日韩精品| 欧美高清在线视频| 亚洲一区二区三区视频| 国产一区二区精品久久99| 欧美高清不卡| 欧美尤物一区| 99re6热只有精品免费观看| 久久福利影视| 99这里只有久久精品视频| 国产欧美日韩综合一区在线播放| 六月婷婷一区| 性伦欧美刺激片在线观看| 亚洲国产精品久久久久秋霞蜜臀| 亚洲女女做受ⅹxx高潮| 亚洲国产精品一区二区尤物区 | 欧美日韩视频专区在线播放| 欧美一区二区三区免费视| 亚洲高清资源综合久久精品| 性色一区二区| 99香蕉国产精品偷在线观看| 国产婷婷色一区二区三区在线| 欧美成人中文字幕| 久久久精品国产一区二区三区| 99riav久久精品riav| 欧美高清视频一二三区| 欧美在线视频a| 亚洲一线二线三线久久久| 91久久黄色| 狠狠入ady亚洲精品经典电影| 国产精品久久久久高潮| 欧美高清在线精品一区| 久久久亚洲人| 久久xxxx| 欧美中文在线观看| 午夜精品免费| 亚洲欧美国产视频| 中文av一区二区| 一本色道久久综合| 亚洲精选一区二区| 亚洲日本在线观看| 亚洲激情av| 亚洲国产成人精品视频| 欧美成人久久| 欧美成人一区二区三区| 男男成人高潮片免费网站| 久久久久免费视频| 久久精品在线免费观看| 欧美制服第一页| 久久国产精品72免费观看| 午夜精品网站| 久久国产精彩视频| 久久精品成人一区二区三区蜜臀| 欧美一区深夜视频| 欧美在线日韩| 久久这里有精品视频| 久久躁狠狠躁夜夜爽| 欧美v国产在线一区二区三区| 老鸭窝毛片一区二区三区| 乱码第一页成人| 亚洲电影在线免费观看| 亚洲国产婷婷香蕉久久久久久| 亚洲激情一区二区| 一本色道久久综合亚洲精品婷婷 | 久久噜噜噜精品国产亚洲综合| 久久国产欧美精品| 久久久在线视频| 欧美精品啪啪| 国产精品久久久久91| 国产亚洲成av人片在线观看桃| 红桃视频欧美| 亚洲精品国产品国语在线app | 国产精品视频网址| 国产综合第一页| 亚洲国产一区二区三区在线播| 亚洲美女一区| 欧美一区网站| 欧美激情1区2区3区| 亚洲乱码国产乱码精品精天堂| 亚洲一区二区三区777| 久久成人精品无人区| 欧美国产三区| 国产日韩精品视频一区| 亚洲破处大片| 欧美一区二区三区四区高清| 欧美大片第1页| 亚洲一二三四久久| 牛人盗摄一区二区三区视频| 国产精品成人观看视频免费 | 在线亚洲免费视频| 久久精品视频在线播放| 亚洲国产精品999| 亚洲欧美一区二区精品久久久| 久久亚洲精品网站| 国产精品福利影院| 亚洲激情欧美激情| 久久国产精品高清| 日韩视频国产视频| 久久久久亚洲综合| 国产精品手机在线| 一区二区毛片| 欧美华人在线视频| 久久精品国产亚洲一区二区三区 | 久色成人在线| 国产欧美日韩麻豆91| 亚洲午夜高清视频|