Android原始碼解析之一 非同步訊息機制

七號座先生發表於2018-03-26

Android原始碼解析之一 非同步訊息機制

1,handler的常規使用方式

/**
 * 測試Activity,主要用於測試非同步訊息(Handler)的使用方式
 */
public class MainActivity extends AppCompatActivity {

    public static final String TAG = MainActivity.class.getSimpleName();
    private TextView texttitle = null;

    /**
     * 在主執行緒中定義Handler,並實現對應的handleMessage方法
     */
    public static Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 101) {
                Log.i(TAG, "接收到handler訊息...");
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        texttitle = (TextView) findViewById(R.id.texttitle);
        texttitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread() {
                    @Override
                    public void run() {
                        // 在子執行緒中傳送非同步訊息
                        mHandler.sendEmptyMessage(101);
                    }
                }.start();
            }
        });
    }
}

複製程式碼

根據上述程式碼可以看出,一般handler的使用方式都是在主執行緒中定義handler,然後在子執行緒中呼叫mHandler.sendEnptyMessage();方法,那麼這裡就有一個疑問了,我們可以在子執行緒中定義handler 嗎?

2,如何在子執行緒中定義Handler ?

我們在子執行緒中定義Handler,看看測試結果:

/**
 * 定義texttitle的點選事件處理
 */
texttitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /**
                 * 定義在子執行緒中執行handler的建立
                 */
                new Thread() {
                    @Override
                    public void run() {
                        Handler mHandler = new Handler() {
                            @Override
                            public void handleMessage(Message msg) {
                                if (msg.what == 101) {
                                    Log.i(TAG, "在子執行緒中定義Handler,並接收到訊息。。。");
                                }
                            }
                        };
                    }
                }.start();
            }
        });

複製程式碼

Android原始碼解析之一 非同步訊息機制

可以看出在子執行緒中定義的Handler物件報錯了,難道Handler物件的定義或者出事中能在主執行緒中?其實不是這樣,錯誤資訊中提示的很明顯了,在初始化Handler物件之前需要呼叫Looper.prepare()方法。

/**
 * 定義texttitle的點選事件處理
 */
texttitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread() {
                    @Override
                    public void run() {
                        Looper.prepare();
                        Handler mHandler = new Handler() {
                            @Override
                            public void handleMessage(Message msg) {
                                if (msg.what == 101) {
                                    Log.i(TAG, "在子執行緒中定義Handler,並接收到訊息。。。");
                                }
                            }
                        };
                    }
                }.start();
            }
        });
        
複製程式碼

再次點選按鈕執行此段程式碼,程式就不會報錯了,那麼這說明初始化Handler物件的時候我們是需要呼叫Looper.prepare()方法的,那麼主執行緒中為什麼可以直接初始化Handler呢?

再次查閱一下原始碼發現,APP初始化的時候會執行ActivityThread 的main方法:

public static void More ...main(String[] args) {
        SamplingProfilerIntegration.start();

       // CloseGuard defaults to true and can be quite spammy.  We
       // disable it here, but selectively enable it later (via
       // StrictMode) on debug builds, but using DropBox, not logs.
       CloseGuard.setEnabled(false);
       // 初始化應用中需要使用的系統路徑
       Environment.initForCurrentUser();

       // Set the reporter for event logging in libcore
       EventLogger.setReporter(new EventLoggingReporter());
       //增加一個儲存key的provider
      Security.addProvider(new AndroidKeyStoreProvider());

      // Make sure TrustedCertificateStore looks in the right place for CA certificates
            //為應用設定當前使用者的CA證書儲存的位置
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);
       //設定程式的名稱
      Process.setArgV0("<pre-initialized>");

        Looper.prepareMainLooper();
       //建立ActivityThread 物件
       ActivityThread thread = new ActivityThread();
       thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
       }

       if (false) {
           Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
       }

        Looper.loop();

       throw new RuntimeException("Main thread loop unexpectedly exited");
   }




複製程式碼

首先Looper.prepareMainLooper();是為主執行緒建立了Looper,然後thread.getHandler();是儲存了主執行緒的Handler,最後Looper.loop();進入訊息迴圈。

3, 檢視Handler原始碼

① 檢視Looper.prepare()方法

// sThreadLocal.get() will return null unless you've called prepare().
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

/** 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中有一個ThreadLocal成員變數,熟悉JDK的同學應該知道,當使用ThreadLocal 維護變數時,ThreadLocal為每個使用該成員的執行緒提供獨立的變數副本,所以每一個執行緒都可以獨立地改變自己的副本,而不會影響其他執行緒所對應的副本。

由此可以看出在每個執行緒中Looper.prepare() 能且只能呼叫一次。

繼續看Looper物件的構造方法,可以看到在其構造方法中初始化了一個MessageQueue物件:

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

複製程式碼

綜上小結①:Looper.prepare()方法初始話了一個Looper物件並關聯在一個MessageQueue物件,並且一個執行緒中只有一個Looper物件,只有一個MessageQueue物件。

② 檢視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;
    }

複製程式碼

可以看出在Handler中的構造方法中,主要初始化了一下變數,並判斷Handler物件的初始化不應在內部類,靜態類,匿名類中,並且儲存了當前執行緒中的Looper物件。

綜上小結② :Looper.prepare()方法初始話了一個Looper物件並關聯在一個MessageQueue物件,並且一個執行緒中只有一個Looper物件,只有一個MessageQueue物件。而Handler的構造方法則在Handler內部維護了當前執行緒的Looper物件

③檢視handler.setMesssage(msg)方法 一般情況下,我們傳送非同步訊息的時候會這樣呼叫:

mHandler.sendMessage(new Message());

通過不斷的跟進原始碼,其最後會呼叫:

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }
    
複製程式碼

原來msg.target就是Handler物件本身;而這裡的queue物件就是我們的Handler內部維護的Looper物件關聯的MessageQueue物件。檢視messagequeue物件的enqueueMessage方法:

boolean enqueueMessage(Message msg, long when) {
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }
        if (msg.isInUse()) {
            throw new IllegalStateException(msg + " This message is already in use.");
        }

        synchronized (this) {
            if (mQuitting) {
                IllegalStateException e = new IllegalStateException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w(TAG, e.getMessage(), e);
                msg.recycle();
                return false;
            }

            msg.markInUse();
            msg.when = when;
            Message p = mMessages;
            boolean needWake;
            if (p == null || when == 0 || when < p.when) {
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                // Inserted within the middle of the queue.  Usually we don't have to wake
                // up the event queue unless there is a barrier at the head of the queue
                // and the message is the earliest asynchronous message in the queue.
                needWake = mBlocked && p.target == null && msg.isAsynchronous();
                Message prev;
                for (;;) {
                    prev = p;
                    p = p.next;
                    if (p == null || when < p.when) {
                        break;
                    }
                    if (needWake && p.isAsynchronous()) {
                        needWake = false;
                    }
                }
                msg.next = p; // invariant: p == prev.next
                prev.next = msg;
            }

            // We can assume mPtr != 0 because mQuitting is false.
            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }
    
複製程式碼

可以看到這裡MessageQueue並沒有使用列表將所有的Message儲存起來,而是使用Message.next儲存下一個Message,從而按照時間將所有的Message排序。

④ 檢視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();
        }
    }
    
複製程式碼

可以看到Looper.loop()方法裡起了一個死迴圈,不斷的判斷MessageQueue中的訊息是否為空,如果為空則直接return掉,然後執行queue.next()方法:


 Message next() {
        // Return here if the message loop has already quit and been disposed.
        // This can happen if the application tries to restart a looper after quit
        // which is not supported.
        final long ptr = mPtr;
        if (ptr == 0) {
            return null;
        }

        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }

            nativePollOnce(ptr, nextPollTimeoutMillis);

            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;
                if (msg != null && msg.target == null) {
                    // Stalled by a barrier.  Find the next asynchronous message in the queue.
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }
                if (msg != null) {
                    if (now < msg.when) {
                        // Next message is not ready.  Set a timeout to wake up when it is ready.
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        // Got a message.
                        mBlocked = false;
                        if (prevMsg != null) {
                            prevMsg.next = msg.next;
                        } else {
                            mMessages = msg.next;
                        }
                        msg.next = null;
                        if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                        msg.markInUse();
                        return msg;
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }

                // Process the quit message now that all pending messages have been handled.
                if (mQuitting) {
                    dispose();
                    return null;
                }

                // If first time idle, then get the number of idlers to run.
                // Idle handles only run if the queue is empty or if the first message
                // in the queue (possibly a barrier) is due to be handled in the future.
                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount <= 0) {
                    // No idle handlers to run.  Loop and wait some more.
                    mBlocked = true;
                    continue;
                }

                if (mPendingIdleHandlers == null) {
                    mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
                }
                mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
            }

            // Run the idle handlers.
            // We only ever reach this code block during the first iteration.
            for (int i = 0; i < pendingIdleHandlerCount; i++) {
                final IdleHandler idler = mPendingIdleHandlers[i];
                mPendingIdleHandlers[i] = null; // release the reference to the handler

                boolean keep = false;
                try {
                    keep = idler.queueIdle();
                } catch (Throwable t) {
                    Log.wtf(TAG, "IdleHandler threw exception", t);
                }

                if (!keep) {
                    synchronized (this) {
                        mIdleHandlers.remove(idler);
                    }
                }
            }

            // Reset the idle handler count to 0 so we do not run them again.
            pendingIdleHandlerCount = 0;

            // While calling an idle handler, a new message could have been delivered
            // so go back and look again for a pending message without waiting.
            nextPollTimeoutMillis = 0;
        }
    }
    
複製程式碼

可以看到其大概的實現邏輯就是Message的出棧操作,裡面可能對執行緒,併發控制做了一些限制等。獲取到棧頂的Message物件之後開始執行:

msg.target.dispatchMessage(msg);

那麼 msg.target 是什麼呢? 痛過追蹤可以知道就是我們定義的Handler物件,然後我們檢視一下Handler類的dispatchMessage 方法:

/**
     * 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(Runnable物件)的話,則會直接呼叫handlerCallback方法:

private static void handleCallback(Message message) {
        message.callback.run();
    }
    
複製程式碼

即,如果我們在初始化Handler的時候設定callback (Runnable)物件,則直接呼叫run方法。 比如我們經常寫的runOnUiThread 方法:

runOnUiThread(new Runnable() {
            @Override
            public void run() {

            }
        });
        
複製程式碼

看起內部實現:

public final void runOnUiThread(Runnable action) {
        if (Thread.currentThread() != mUiThread) {
            mHandler.post(action);
        } else {
            action.run();
        }
    }

複製程式碼

而如果msg.callback為空的話,會直接呼叫我們的mCallback.handleMessage(msg),即handler的handlerMessage方法。由於Handler物件是在主執行緒中建立的,所以handler的handlerMessage方法的執行也會在主執行緒中。

總結

  • 主執行緒中定義Handler,直接執行:
Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
               super.handleMessage(msg);
        }
};

複製程式碼

而如果想要在子執行緒中定義Hanlder,則標準寫法為:

// 初始化該執行緒Looper,MessageQueue,執行且只能執行一次
                Looper.prepare();
                // 初始化Handler物件,內部關聯Looper物件
                Handler mHandler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                    }
                };
                // 啟動訊息佇列出棧死迴圈
                Looper.loop();
                
複製程式碼
  • 一個執行緒中只存在一個Looper物件,只存在一個MessageQueue物件,可以存在N個Handler物件,Handler物件內部關聯了本執行緒中唯一的Looper物件,Looper物件內部關聯著唯一的一個MessageQueue物件。

  • MessageQueue訊息佇列不是通過列表儲存訊息列表的,而且通過Message物件next屬性關聯下一個Message 從而實現列表的功能,同時所有的訊息都是按時間來排序的。

  • Android中兩個子執行緒相互互動同樣可以通過Handler的非同步訊息機制實現,可以線上程A中定義Handler物件,而線上程B中獲取handler的引用並呼叫sendMessage方法。

  • activity內部預設存在一個handler的成員變數,Android中的一些其他的非同步訊息機制實現方法:

Handler的post方法:

mHandler.post(new Runnable() {
                    @Override
                    public void run() {

                    }
                });
                
複製程式碼

檢視其內部實現:

public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }
    
複製程式碼

可以發現其內部呼叫就是sendMessage系列方法。

view的post方法:

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;
    }

複製程式碼

可以發現其呼叫的就是activity中預設儲存的handler物件的post方法。

activity的runOnUiThread方法:

public final void runOnUiThread(Runnable action) {
        if (Thread.currentThread() != mUiThread) {
            mHandler.post(action);
        } else {
            action.run();
        }
    }

複製程式碼

判斷當前執行緒是否是UI執行緒,如果不是,則呼叫handler的post方法,否則直接執行run方法。

相關文章