android分析之訊息處理

來源:互聯網
上載者:User

標籤:des   android   style   blog   color   io   os   使用   java   

前序:每個APP對應一個進程,該進程內有一個ActivityThread的線程,稱為主線程(即UI主線程),此外,還有其他線程,這個再論。

 

android的訊息系統分析。

  1. 每個Thread只對應一個Looper
  2. 每個Looper只對應一個MessageQueue
  3. 每個MessageQueue中有N個Message
  4. 每個Message中最多指定一個Handler來處理事件
  5. 一個Thread可以對應多個Handler

Looper負責從訊息佇列中(MessageQueue)取出訊息(Message/Runnable),交給Handler來處理。

 

Message:

public final class Message implements Parcelable {
public int what;//每個Message可以指定一個Handler,由於可以存在多個Handler,用what來標識具體的Handler public int arg1; public int arg2; public Object obj; public Messenger replyTo; /*package*/ static final int FLAG_IN_USE = 1 << 0; /*package*/ static final int FLAG_ASYNCHRONOUS = 1 << 1; /*package*/ static final int FLAGS_TO_CLEAR_ON_COPY_FROM = FLAG_IN_USE; /*package*/ int flags; /*package*/ long when; /*package*/ Bundle data; /*package*/ Handler target;//指定由哪個Handler來處理本Message /*package*/ Runnable callback; /*package*/ Message next;//訊息鏈 private static final Object sPoolSync = new Object(); private static Message sPool;//訊息鏈表的頭,注意是static private static int sPoolSize = 0; private static final int MAX_POOL_SIZE = 50;

......

}

 

MessageQueue實際上是對Message的一種操作的封裝,真正的訊息佇列是以sPool為首的訊息鏈表:

public class MessageQueue {    // True if the message queue can be quit.    private final boolean mQuitAllowed;    @SuppressWarnings("unused")    private int mPtr; // used by native code    Message mMessages;//訊息...    private final ArrayList<IdleHandler> mIdleHandlers = new ArrayList<IdleHandler>();    private IdleHandler[] mPendingIdleHandlers;    private boolean mQuiting;    // Indicates whether next() is blocked waiting in pollOnce() with a non-zero timeout.    private boolean mBlocked;    // The next barrier token.    // Barriers are indicated by messages with a null target whose arg1 field carries the token.    private int mNextBarrierToken;
//調用Native函數做真正的處理 private native void nativeInit(); private native void nativeDestroy(); private native void nativePollOnce(int ptr, int timeoutMillis); private native void nativeWake(int ptr);
......

}

 

  Looper:

public class Looper {    private static final String TAG = "Looper";    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();//與線程相關的模板類    private static Looper sMainLooper;  //static類型,只有一個    final MessageQueue mQueue;//Looper持有的MessageQueue    final Thread mThread;    volatile boolean mRun;    private Printer mLogging;

......

}

  

Handler:

public class Handler{//真正對處理Message的類:包括處理Message和將訊息壓到MessageQueue隊列裡    final MessageQueue mQueue;    final Looper mLooper;    final Callback mCallback;    IMessenger mMessenger;...}

  

Looper的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;        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);//調用訊息指定的接收者Handler來處理它            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.recycle();//丟棄訊息,迴圈再利用        }    }

  Handler取訊息,每次從sPool(Message裡的static Message類型)取出一個Message,其調用的是static方法:

    public static Message obtain(Handler h, int what, Object obj) {        Message m = obtain();        m.target = h;        m.what = what;        m.obj = obj;        return m;    }

  Handler將訊息壓入訊息佇列:

    public boolean sendMessageAtTime(Message msg, long uptimeMillis)    {        boolean sent = false;        MessageQueue queue = mQueue;        if (queue != null) {            msg.target = this;            sent = queue.enqueueMessage(msg, uptimeMillis);//調用MessageQueue的方法執行壓入操作        }        else {            RuntimeException e = new RuntimeException(                this + " sendMessageAtTime() called with no mQueue");            Log.w("Looper", e.getMessage(), e);        }        return sent;    }

  小結:Handler取訊息是直接取(從sPool裡),將訊息壓入MessageQueue是調用MessageQueue的方法。

----------------------------------------------分割線----------------------------------------------------------------------------

下面分析這些對象都是在什麼時候建立的。

Looper是什麼時候建立的?

每個線程都只有一個Looper對象。

1.普通線程(非主線程)

一個典型的自己建立的線程使用Looper如:

class LooperThread extends Thread{    public Handler mHandler;    public void run(){        Looper.prepare();        mHandler= new Handler(){                public void handleMessage(Message msg){                    //處理訊息                }        };        Looper.loop();//進入訊息迴圈    }}

  那麼Looper是在什麼時候建立的呢?看Looper.prepare()方法:執行完這個方法,就得到了一個本線程專屬的Looper。

static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();//這是一個與線程先關的模板類    

private static void prepare(boolean quitAllowed) { if (sThreadLocal.get() != null) {//若調用者所在宿主線程已經有Looper,則拋出異常 throw new RuntimeException("Only one Looper may be created per thread"); } sThreadLocal.set(new Looper(quitAllowed));//Java中的線程局部儲存,即不同線 }//程都通過sThreadLocal得到自己的不同的Looper對象引用

    private Looper(boolean quitAllowed) {        mQueue = new MessageQueue(quitAllowed);//建立Looper要處理的訊息佇列        mRun = true;        mThread = Thread.currentThread();//得到當前線程    }

  

  那麼Handler是如何與Looper關聯起來的呢?看Handler的構造方法:

public Handler() {        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();//通過線程局部儲存,獲得本線程的Looper        if (mLooper == null) {            throw new RuntimeException(                "Can‘t create handler inside thread that has not called Looper.prepare()");        }        mQueue = mLooper.mQueue;        mCallback = null;    }
    public static Looper myLooper() {//擷取與本線程相關的Looper        return sThreadLocal.get();    }

  

  小結:每個線程都通過sThreadLocal<Looper>來建立一個Looper(進而建立一個MessageQueue),再建立一個Handler(通過sThreadLocal),從而將Handler與Looper“綁定”在一起,形成一個完整的訊息迴圈系統。

 

2.主線程ActivityThread

主線程是什麼時候建立Looper的?在ActivityThread.java的main方法裡有:

    public static void main(String[] args) {        SamplingProfilerIntegration.start();        CloseGuard.setEnabled(false);        Process.setArgV0("<pre-initialized>");        Looper.prepareMainLooper();//也是sThreadLocal.set(new Looper(quitAllowed))來建立一個線程所屬的Looper,並通過sThreadLocal.get()將Looper賦給sMainLooper(private static Looper sMainLooper),sMainLooper的作用就是,其他線程可以擷取到主線程的Looper(因為sMainLooper是static,在主線程中賦值的)。        if (sMainThreadHandler == null) {            sMainThreadHandler = new Handler();        }        ActivityThread thread = new ActivityThread();        thread.attach(false);        AsyncTask.init();        if (false) {            Looper.myLooper().setMessageLogging(new                    LogPrinter(Log.DEBUG, "ActivityThread"));        }        Looper.loop();        throw new RuntimeException("Main thread loop unexpectedly exited");    }

  

Looper.loop()是一個static的方法,作為訊息迴圈處理器,不斷的取訊息,分發訊息。

 

android分析之訊息處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.