異步通訊,消息傳遞
public class HandlerActivity extends AppCompatActivity { Handler handler = new Handler() { @Override public void handleMessage(Message msg) { Toast.makeText(HandlerActivity.this, "接收到了消息", Toast.LENGTH_SHORT).show(); } }; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_handler); } public void onClickView(View v) { switch (v.getId()) { case R.id.button: { Thread thread = new Thread() { @Override public void run() { Message msg = Message.obtain(); handler.sendMessage(msg); } }; thread.start(); break; } } } }
這個界面只有一個Button, 點擊事件是:啓動一個線程,在這個線程裏使用handler,發送一個消息;這個消息不帶任何數據。
Message: 這個能夠使用new來生成,可是最好仍是使用Message.obtain()來獲取一個實例。這樣便於消息池的管理。
handler初始化的時候,咱們複寫了handleMessage方法,這個方法用來接收,子線程中發過來的消息。java
public class HandlerActivity extends AppCompatActivity { Handler handler = new Handler() { @Override public void handleMessage(Message msg) { Log.d("child", "----" + Thread.currentThread().getName()); } }; Handler childHandler = null; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_handler); Thread child = new Thread("child thread") { @Override public void run() { Looper.prepare(); childHandler = new Handler(Looper.myLooper()) { @Override public void handleMessage(Message msg) { Log.d("child", "----" + Thread.currentThread().getName() + ", " + msg.obj); } }; Looper.loop(); } }; child.start(); } public void onClickView(View v) { switch (v.getId()) { case R.id.button: { Thread thread = new Thread() { @Override public void run() { Message msg = Message.obtain(); handler.sendMessage(msg); } }; thread.start(); break; } case R.id.button1: { if (childHandler != null) { Message msg = Message.obtain(childHandler); msg.obj = "123---" + SystemClock.uptimeMillis(); childHandler.sendMessage(msg); } else { Log.d("-----", "onClickView: child Handler is null"); } break; } } } }
主線程向子線程發送消息時,咱們須要使用的是handler,可是這個handler是須要在子線程中實例化,不然子線程沒法接收到消息。
在child thread中準備的工做:app
Looper.loop()調用
假如咱們直接在子線程中直接實例化一個handler,而不傳入Looper實例。程序會直接拋出異常:java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
這個異常是在hanlder源碼:less
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須要一個Looper實例。異步
首先看Looper源碼中是怎麼寫的。Looper的構造方法是私有的,這樣咱們只能經過Looper的靜態方法來實例化一個Looper.在Looper類中還有一個ThreadLocal<Looper> sThreadLocal 變量,而在上面的代碼中使用了Looper.myLooper()方法來給handler一個Looper實例。async
public static @Nullable Looper myLooper() { return sThreadLocal.get(); }
這個方法返回了一個存放在ThreadLocal<Looper>中的Looper實例。ide
Looper.prepare源碼:oop
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));
}
方法很簡單,就是檢查sThreadLocal裏面是否有有值,而後將Looper的實例存放到ThreadLocal,若是不爲空,直接就是 RuntimeException 異常。這也保證了一個線程中只能有一個Looper實例。所以,Looper.prepare方法只能調用一次。ui
在這個程序中,能夠大概理解成線程間數據的隔離。意思就是我存放在ThreadLocal中的數據,只能在我本線程中能夠得到到值,在其餘線程中獲取不到(其餘線程中獲取的是null)。
這樣就能得出,其餘線程中的Looper,在本線程中經過Looper.myLooper()獲取不到數據。this
經過查找Android源碼,能夠知道在ActivityThread中main方法裏面,UI線程已經初始化了Looper.prepareMainLooper();這樣就在UI線程中有Looper實例了。固然在main方法的下面,也調用了Looper.loop()方法。spa
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 final Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs; final long traceTag = me.mTraceTag; if (traceTag != 0 && Trace.isTagEnabled(traceTag)) { Trace.traceBegin(traceTag, msg.target.getTraceName(msg)); } final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis(); final long end; try { msg.target.dispatchMessage(msg); end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis(); } finally { if (traceTag != 0) { Trace.traceEnd(traceTag); } } if (slowDispatchThresholdMs > 0) { final long time = end - start; if (time > slowDispatchThresholdMs) { Slog.w(TAG, "Dispatch took " + time + "ms on " + Thread.currentThread().getName() + ", h=" + msg.target + " cb=" + msg.callback + " msg=" + msg.what); } } 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(); **}**
}
這個方法裏面,咱們須要注意到:
msg.target.dispatchMessage(msg);
for循環是一個死循環,這個須要一直取出MessageQueue隊列中的數據,也就是剛纔所列的第三個 queue.next方法。這個方法會阻塞,直到有消息從消息隊列中取出來。
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; }
}
public void dispatchMessage(Message msg) {<br/>if (msg.callback != null) {<br/>handleCallback(msg);<br/>} else {<br/>if (mCallback != null) {<br/>if (mCallback.handleMessage(msg)) {<br/>return;<br/>}<br/>}<br/>handleMessage(msg);<br/>}<br/>}<br/>
Handler 經過sendMessage方法發送消息。這個方法最終調用的是
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {<br/>msg.target = this;<br/>if (mAsynchronous) {<br/>msg.setAsynchronous(true);<br/>}<br/>return queue.enqueueMessage(msg, uptimeMillis);<br/>}<br/>
參數:MessageQueue queue則是Handler中mQueue變量,這個變量在Handler(Callback callback, boolean async)初始化完成。它是Looper中一個final MessageQueue的變量,在初始化Looper的時候,就開始初始化MessageQueue。這也是一個線程中只有一個MessageQueue的緣由.
Message msg 是封裝的消息。
long uptimeMillis 延遲發送時間。
以前分析looper.loop方法的時候,說了msg.target.dispatchMessage, 這個target就是在這個方法裏面賦值的。
從這個方法裏面,能夠知道handler的sendMessage,只是把消息(Message實例)添加到了queue隊列中。
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; }
經過handler發送Message,將Message壓入MessageQueue隊列中;而Looper.loop方法又在不停的循環這個消息隊列,取出壓入MessageQueue的Message, 而後dispatchMessage分發,最終會調用handler.handleMessage方法來處理髮送過來的Message.