Android線程間通信機制

借用別人的圖如下:
這裏寫圖片描述
1.Message
線程間通信就是在傳遞消息,Message就是消息的載體。常用的有四個字段:
arg1 , arg2 , what ,obj 。源代碼如下:

 /**
     * User-defined message code so that the recipient can identify
     * what this message is about. Each {@link Handler} has its own name-space
     * for message codes, so you do not need to worry about yours conflicting
     * with other handlers.
     */
    public int what;

    /**
     * arg1 and arg2 are lower-cost alternatives to using
     * {@link #setData(Bundle) setData()} if you only need to store a
     * few integer values.
     */
    public int arg1;

    /**
     * arg1 and arg2 are lower-cost alternatives to using
     * {@link #setData(Bundle) setData()} if you only need to store a
     * few integer values.
     */
    public int arg2;

    /**
     * An arbitrary object to send to the recipient.  When using
     * {@link Messenger} to send the message across processes this can only
     * be non-null if it contains a Parcelable of a framework class (not one
     * implemented by the application).   For other data transfer use
     * {@link #setData}.
     *
     * <p>Note that Parcelable objects here are not supported prior to
     * the {@link android.os.Build.VERSION_CODES#FROYO} release.
     */
    public Object obj;

其中obj可以攜帶Object對象,其餘三個可以攜帶整形數據。
2.MessageQueue
MessageQueue是消息隊列,他主要用於存放所有通過Handler發送的消息(就是每個Message),這部分消息會一直存在於消息隊列中,等待被處理。每個線程中只會有一個MessageQueue對象。
3.Looper
每個線程通過Handler發送的消息都保存在MessageQueue中,Looper通過調用loop()方法,就會進入到一個無限循環當中,然後每當發現MessageQueue中存在一條消息,就會將它取出,並傳遞到Handler的HandleMessage()方法中。每個線程中只會有一個Looper對象。
4.Handler
他主要用於發送和處理消息,一般使用senfMessage()方法,還有其他的sendXXX的方法,最終都是調用了sendMessageAtTime()方法,除了sendMessageAtFrontOfQueue()方法,只要實現了Looper的線程構建Handler類,那麼這個Handler實例就獲取該Looper線程MessageQueue實例的引用,Handler 在sendMessage()的時候就通過這個引用往消息隊列裏插入新消息。

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