Android線程間的通信是使用消息機制來實現的。線程通過Looper建立自己的消息迴圈, 對應MessageQueue。 MessageQueue是FIFO的消息隊列。Looper負責從MessageQueue中取出消息,並且分發到消息指定的目標Handler對象,由Handler對象對Messa ...
Android線程間的通信是使用消息機制來實現的。線程通過Looper建立自己的消息迴圈, 對應MessageQueue。 MessageQueue是FIFO的消息隊列。Looper負責從MessageQueue中取出消息,並且分發到消息指定的目標Handler對象,由Handler對象對Message進行處理。
每個app都有自己對應的MessageQueue.
每個線程有且最多只能有一個Looper對象,它是一個ThreadLocal
一個線程對應一個Looper(消息迴圈),一個MessageQueue(消息隊列)
Looper對象的創建是通過prepare函數,而且每一個Looper對象會和一個線程關聯.
Looper對象創建時會創建一個MessageQueue,主線程預設會創建一個Looper從而有MessageQueue,其他線程預設是沒有 MessageQueue的不能接收Message,如果需要接收Message則需要通過prepare函數創建一個MessageQueue。
Looper內部有一個消息隊列,loop()方法調用後線程開始不斷從隊列中取出消息執行
Loop函數從MessageQueue中從前往後取出Message,然後通過Handler的dispatchMessage函數進行消息的處理(可見消息的處理是Handler負責的),消息處理完了以後通過Message對象的recycle函數放到Message Pool中,以便下次使用,通過Pool的處理提供了一定的記憶體管理從而加速消息對象的獲取
Looper使一個線程變成Looper線程。
Looper是線程用來運行消息迴圈的。線程本身是沒有消息迴圈的,需要線上程中調用prepare函數,然後調用loop去處理消息。
主要是下麵四隻文件:
frameworks\base\core\java\android\os\Looper.java
frameworks\base\core\java\android\os\Handler.java
frameworks\base\core\java\android\os\MessageQueue.java
frameworks\base\core\java\android\os\Message.java
/frameworks/base/core/java/android/os/Handler.java
192 public Handler(Callback callback, boolean async) {
193 if (FIND_POTENTIAL_LEAKS) {
194 final Class<? extends Handler> klass = getClass();
195 if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
196 (klass.getModifiers() & Modifier.STATIC) == 0) {
197 Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
198 klass.getCanonicalName());
199 }
200 }
201
202 mLooper = Looper.myLooper();
203 if (mLooper == null) {
204 throw new RuntimeException(
205 "Can't create handler inside thread that has not called Looper.prepare()");
206 }
207 mQueue = mLooper.mQueue;
208 mCallback = callback;
209 mAsynchronous = async;
210 }
/frameworks/base/core/java/android/os/MessageQueue.java
309 Message next() {
310 // Return here if the message loop has already quit and been disposed.
311 // This can happen if the application tries to restart a looper after quit
312 // which is not supported.
313 final long ptr = mPtr;
314 if (ptr == 0) {
315 return null;
316 }
317
318 int pendingIdleHandlerCount = -1; // -1 only during first iteration
319 int nextPollTimeoutMillis = 0;
320 for (;;) {
321 if (nextPollTimeoutMillis != 0) {
322 Binder.flushPendingCommands();
323 }
324
325 nativePollOnce(ptr, nextPollTimeoutMillis);
326
327 synchronized (this) {
328 // Try to retrieve the next message. Return if found.
329 final long now = SystemClock.uptimeMillis();
330 Message prevMsg = null;
331 Message msg = mMessages;
332 if (msg != null && msg.target == null) {
333 // Stalled by a barrier. Find the next asynchronous message in the queue.
334 do {
335 prevMsg = msg;
336 msg = msg.next;
337 } while (msg != null && !msg.isAsynchronous());
338 }
339 if (msg != null) {
340 if (now < msg.when) {
341 // Next message is not ready. Set a timeout to wake up when it is ready.
342 nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
343 } else {
344 // Got a message.
345 mBlocked = false;
346 if (prevMsg != null) {
347 prevMsg.next = msg.next;
348 } else {
349 mMessages = msg.next;
350 }
351 msg.next = null;
352 if (DEBUG) Log.v(TAG, "Returning message: " + msg);
353 msg.markInUse();
354 return msg;
355 }
356 } else {
357 // No more messages.
358 nextPollTimeoutMillis = -1;
359 }
360
361 // Process the quit message now that all pending messages have been handled.
362 if (mQuitting) {
363 dispose();
364 return null;
365 }
366
367 // If first time idle, then get the number of idlers to run.
368 // Idle handles only run if the queue is empty or if the first message
369 // in the queue (possibly a barrier) is due to be handled in the future.
370 if (pendingIdleHandlerCount < 0
371 && (mMessages == null || now < mMessages.when)) {
372 pendingIdleHandlerCount = mIdleHandlers.size();
373 }
374 if (pendingIdleHandlerCount <= 0) {
375 // No idle handlers to run. Loop and wait some more.
376 mBlocked = true;
377 continue;
378 }
379
380 if (mPendingIdleHandlers == null) {
381 mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
382 }
383 mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
384 }
385
386 // Run the idle handlers.
387 // We only ever reach this code block during the first iteration.
388 for (int i = 0; i < pendingIdleHandlerCount; i++) {
389 final IdleHandler idler = mPendingIdleHandlers[i];
390 mPendingIdleHandlers[i] = null; // release the reference to the handler
391
392 boolean keep = false;
393 try {
394 keep = idler.queueIdle();
395 } catch (Throwable t) {
396 Log.wtf(TAG, "IdleHandler threw exception", t);
397 }
398
399 if (!keep) {
400 synchronized (this) {
401 mIdleHandlers.remove(idler);
402 }
403 }
404 }
405
406 // Reset the idle handler count to 0 so we do not run them again.
407 pendingIdleHandlerCount = 0;
408
409 // While calling an idle handler, a new message could have been delivered
410 // so go back and look again for a pending message without waiting.
411 nextPollTimeoutMillis = 0;
412 }
413 }
535 boolean enqueueMessage(Message msg, long when) {
536 if (msg.target == null) {
537 throw new IllegalArgumentException("Message must have a target.");
538 }
539 if (msg.isInUse()) {
540 throw new IllegalStateException(msg + " This message is already in use.");
541 }
542
543 synchronized (this) {
544 if (mQuitting) {
545 IllegalStateException e = new IllegalStateException(
546 msg.target + " sending message to a Handler on a dead thread");
547 Log.w(TAG, e.getMessage(), e);
548 msg.recycle();
549 return false;
550 }
551
552 msg.markInUse();
553 msg.when = when;
554 Message p = mMessages;
555 boolean needWake;
556 if (p == null || when == 0 || when < p.when) {
557 // New head, wake up the event queue if blocked.
558 msg.next = p;
559 mMessages = msg;
560 needWake = mBlocked;
561 } else {
562 // Inserted within the middle of the queue. Usually we don't have to wake
563 // up the event queue unless there is a barrier at the head of the queue
564 // and the message is the earliest asynchronous message in the queue.
565 needWake = mBlocked && p.target == null && msg.isAsynchronous();
566 Message prev;
567 for (;;) {
568 prev = p;
569 p = p.next;
570 if (p == null || when < p.when) {
571 break;
572 }
573 if (needWake && p.isAsynchronous()) {
574 needWake = false;
575 }
576 }
577 msg.next = p; // invariant: p == prev.next
578 prev.next = msg;
579 }
580
581 // We can assume mPtr != 0 because mQuitting is false.
582 if (needWake) {
583 nativeWake(mPtr);
584 }
585 }
586 return true;
587 }
/frameworks/base/core/java/android/os/Looper.java
129 public static void loop() {
130 final Looper me = myLooper();
131 if (me == null) {
132 throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
133 }
134 final MessageQueue queue = me.mQueue;
135
136 // Make sure the identity of this thread is that of the local process,
137 // and keep track of what that identity token actually is.
138 Binder.clearCallingIdentity();
139 final long ident = Binder.clearCallingIdentity();
140
141 for (;;) {
142 Message msg = queue.next(); // might block
143 if (msg == null) {
144 // No message indicates that the message queue is quitting.
145 return;
146 }
147
148 // This must be in a local variable, in case a UI event sets the logger
149 final Printer logging = me.mLogging;
150 if (logging != null) {
151 logging.println(">>>>> Dispatching to " + msg.target + " " +
152 msg.callback + ": " + msg.what);
153 }
154
155 final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
156
157 final long traceTag = me.mTraceTag;
158 if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
159 Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
160 }
161 final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
162 final long end;
163 try {
164 msg.target.dispatchMessage(msg);
165 end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
166 } finally {
167 if (traceTag != 0) {
168 Trace.traceEnd(traceTag);
169 }
170 }
171 if (slowDispatchThresholdMs > 0) {
172 final long time = end - start;
173 if (time > slowDispatchThresholdMs) {
174 Slog.w(TAG, "Dispatch took " + time + "ms on "
175 + Thread.currentThread().getName() + ", h=" +
176 msg.target + " cb=" + msg.callback + " msg=" + msg.what);
177 }
178 }
179
180 if (logging != null) {
181 logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
182 }
183
184 // Make sure that during the course of dispatching the
185 // identity of the thread wasn't corrupted.
186 final long newIdent = Binder.clearCallingIdentity();
187 if (ident != newIdent) {
188 Log.wtf(TAG, "Thread identity changed from 0x"
189 + Long.toHexString(ident) + " to 0x"
190 + Long.toHexString(newIdent) + " while dispatching to "
191 + msg.target.getClass().getName() + " "
192 + msg.callback + " what=" + msg.what);
193 }
194
195 msg.recycleUnchecked();
196 }
197 }
1. Handler可以在任意線程發送消息,這些消息會被添加到關聯的Message Queue上.
2. Handler是在它關聯的Looper線程中處理消息的.
3. 開發者需要重寫Handler的handleMessage().
Message Structure
一個線程只有一個消息迴圈looper和一個消息隊列;但是可以有多個handler,那麼如何區分消息發送給誰處理呢?
每個消息中都有target對應的handler對象
將消息壓入消息隊列: Message對象的target欄位關聯了哪個線程的消息隊列, 這個消息就會被壓入哪個線程的消息隊列中.
調用Handler對象的方法入隊的Message(最終都會調用enqueueMessage), 其target屬性會被賦值為這個handler對象.
調用Handler類中以send開頭的方法可以將Message對象壓入消息隊列中;
調用Handler類中以post開頭的方法可以將一個runnable對象包裝在一個Message對象中, 然後再壓入消息隊列, 此時入隊的Message其callback欄位不為null, 值就是這個runnable對象.
調用Message對象的sendToTarget()方法可以將其本身壓入與其target欄位(即handler對象)所關聯的消息隊列 中.
從消息隊列中取出消息並處理消息: 所有在消息隊列中的消息, 都具有target欄位. 消息是在target所關聯的線程上被取出和處理的.