android源碼解析(3)--handler消息機制

            最近正在找工作,正好也有時候整理整理知識點。今天整理一下Android的消息機制,這個也是面試當中必問的知識點了。

           1.先看看我們是如何使用的

    public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mLooperThread = new LooperThread("回家");
        mLooperThread.start();
    }

    /**
     * 1.最常規用法,使用在主線程中直接new一個,然後發送消息
     */
    private Handler mMainHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Log.e("TAG", "handleMessage: " + Thread.currentThread().getName());
        }
    };

    /**
     * 2.在分線程中使用方法
     */
    private LooperThread mLooperThread;

    class LooperThread extends Thread {
        public Handler mHandler;

        public LooperThread(String name) {
            super(name);
        }

        public void run() {
            //第一步
            Looper.prepare();
            //第二步
            mHandler = new Handler() {
                public void handleMessage(Message msg) {
                    Log.e("TAG", "handleMessage: " + Thread.currentThread().getName());
                }
            };
            //第三步
            Looper.loop();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mLooperThread.mHandler.sendEmptyMessageDelayed(1, 1000);
        mMainHandler.sendEmptyMessageDelayed(1, 1000);
    }
   }
      2.具體怎麼使用不用多說,然後我們來分析一下原理,還是從分線程中的使用開始分析,因爲分線程可以說是最中規中矩的用法,主線程待會再說

         1)第一步Looper.prepare();方法,那麼他到底做了什麼呢?看源碼

    final MessageQueue mQueue;
    final Thread mThread;

    private Printer mLogging;

     /** 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));
    }
我們可以看到,這個方法有三個功能,第一就是new Looper,第二就是將這個looper和當前的thread綁定,我認爲和我們平時給view設置tag一樣,目的就是爲了便於查找綁定,同時也說明Looper所在的線程纔是我們需要處理結果的線程,這個待會驗證。第三個功能就是創建之前的判斷,如果當前線程中已經綁定過looper了,那就會拋異常。然後看看new looper做了什麼呢:

    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }
好像也很簡單,就是創建了一個消息隊列,但是注意這個消息隊列可是Looper的一個屬性,也就是說完成了Looper和消息隊列的綁定。

       2)第二步:創建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()方法:

    /**
     * Return the Looper object associated with the current thread.  Returns
     * null if the calling thread is not associated with a Looper.
     */
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }
是不是就是返回當前線程綁定的Looper,也就是說handler創建所在線程綁定的looper(當然我們也可以指定其他線程looper,下面再說),這樣就把handler、looper、messagequeue三者綁定到一起了。

        3)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;

        // 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();
        }
    }
一堆代碼其實就幾行我們需要,首先開啓了死循環去消息隊列中不停的取消息,注意這裏queue.next()方法是可以阻塞的,也就是說如果有消息來了他就會自動喚醒,沒有消息了,就是自動釋放cpu資源直到有消息來了再次喚醒,這個就要研究linux了(本人不懂)。繼續,如果取到消息了,就會進入msg.target進行處理,其實就是handler自己,待會看;但是如果msg爲null的時候呢,就會跳出循環,結束掉,什麼情況會執行呢,就是looper.quit()執行後,就會結束掉,重新開啓應該再次調用此方法。好了,總之這裏就是有了消息就交給handler處理。

         現在是消息隊列也有了,looper也開始工作不停的取消息了,handler也等待着處理消息了,那麼就差我們發消息了。

     mMainHandler.sendEmptyMessageDelayed(1, 1000);
消息來了,那麼是怎麼發的呢?我們可以看看源碼:

    /**
     * Sends a Message containing only the what value, to be delivered
     * after the specified amount of time elapses.
     * @see #sendMessageDelayed(android.os.Message, long) 
     * 
     * @return Returns true if the message was successfully placed in to the 
     *         message queue.  Returns false on failure, usually because the
     *         looper processing the message queue is exiting.
     */
    public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
        Message msg = Message.obtain();
        msg.what = what;
        return sendMessageDelayed(msg, delayMillis);
    }
繼續:

    public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }
繼續:
    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);
    }
這裏取到了Looper中的消息隊列了,然後開始向隊列中塞入數據:
    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

         關鍵點來了,第一行代碼給mag設置了一個target,就是當前的handler,還記得剛纔取出來消息處理是不是調用的msg.target.dispatchMessage()方法,不就是又交給handler自己處理了嗎!這裏再說一下消息隊列裏的消息其實是根據延遲時間來進行排序,並不是真正的隊列先進後出原則。好了整個過程就分析完了,現在我們就可以在任意一個分線程中發送消息,然後會回到Looper所在的線程中處理結果,這樣就實現了跨線程的通信。

        忘了把handler分發事件處理的代碼貼出來了:

    /**
     * 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);
        }
    }
這裏我們可以看到,其實handler裏面我們重寫的那個方法級別最低了。

       4)爲什麼說Looper所在的線程纔是決定處理消息的線程呢,我麼可以驗證一下:

    class LooperThread extends Thread {
        public Handler mHandler;

        public LooperThread(String name) {
            super(name);
        }

        public void run() {
            //第一步
            Looper.prepare();
            //第二步
            mHandler = new Handler(getMainLooper()) {
                public void handleMessage(Message msg) {
                    Log.e("TAG", "handleMessage: " + Thread.currentThread().getName());
                }
            };
            //第三步
            Looper.loop();
        }
    }
這裏只變化了一點,那就是創建handler的時候我們將主線程的looper穿進去了,那麼handler再處理消息就也跑到主線程去了,而如果向我們最開始一樣使用空參構造器則會使用當前線程的looper,所以說looper所在的線程纔是真正最後結果處理完所在的線程。至於爲什麼,因爲looper纔是真正和線程關聯在一起的,而handler是和looper關聯在一起的,handler是通過looper間接和線程關聯的。

       2.使用中、面試中的問題:

         1)既然looper裏面是個死循環,爲什麼不會阻塞主線程呢?這個問題上面已經說過了。

         2)如果最開始上面的使用方法,AS會提示內存泄漏的,確實也會存在,解決方法有如下兩種:

         第一種:

    @Override
    protected void onDestroy() {
        mMainHandler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }
這種方法一般情況下沒有問題,但是如果activity銷燬的時候不調用此方法該怎麼辦呢?(極個別手機在極端情況下確實存在不走這個方法),如果忽略可以這麼做。

       第二種方法:

    private static class MyHandler extends Handler {  
        private final WeakReference<HandlerActivity2> mActivity;  
  
        public MyHandler(HandlerActivity2 activity) {  
            mActivity = new WeakReference<HandlerActivity2>(activity);  
        }  
  
        @Override  
        public void handleMessage(Message msg) {   
            if (mActivity.get() == null) {  
                return;  
            }  
            mActivity.get().todo();  
        }  
    }  
網上抄的一段代碼,不過確實是這麼解決使用弱引用來解決,但是問題是弱引用容易被回收啊,那就會導致我本來應該處理一段邏輯,但是由於內存緊張弱引用被回收了,邏輯也處理不了了,那悲劇了!所以這種也不是百分之百好。

       

        






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章