天天看點

全面解析Android進階面試常客之Handler

閱讀本文後你将會有以下收獲:

  • 清楚的了解Handler的工作原理
  • 理清Handler、Message、MessageQueue以及Looper之間的關系
  • 知道Looper是怎麼和目前線程進行綁定的
  • 是否能在子線程中建立Handler
  • 獲得分析Handler源碼的思路

要想有以上的收獲,就需要研究Handler的源碼,從源碼中來得到答案。

開始探索之路

Handler的使用

先從Handler的使用開始。我們都知道Android的主線程不能處理耗時的任務,否者會導緻ANR的出現,但是界面的更新又必須要在主線程中進行,這樣,我們就必須在子線程中處理耗時的任務,然後在主線程中更新UI。

但是,我們怎麼知道子線程中的任務何時完成,又應該什麼時候更新UI,又更新什麼内容呢?為了解決這個問題,Android為我們提供了一個消息機制即Handler。下面就看下Handler的常見使用方式,代碼如下

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
 private Button mStartTask;
 @SuppressLint("HandlerLeak")
 private Handler mHandler = new Handler() {
 @Override
 public void handleMessage(Message msg) {
 super.handleMessage(msg);
 if (msg.what == 1) {
 Toast.makeText(MainActivity.this, "重新整理UI、", Toast.LENGTH_SHORT).show();
 }
 }
 };
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 initView();
 }
 private void initView() {
 mStartTask = findViewById(R.id.btn_start_task);
 mStartTask.setOnClickListener(this);
 }
 @Override
 public void onClick(View v) {
 switch (v.getId()) {
 case R.id.btn_start_task:
 new Thread(new Runnable() {
 @Override
 public void run() {
 try {
 Thread.sleep(1000);
 mHandler.sendEmptyMessage(1);
 } catch (InterruptedException e) {
 e.printStackTrace();
 }
 }
 }).start();
 break;
 }
 }
}           

可以看到在子線程中,讓線程睡了一秒,來模仿耗時的任務,當耗時任務處理完之後,Handler會發送一個消息,然後我們可以在Handler的handleMessage方法中得到這個消息,得到消息之後就能夠在handleMessage方法中更新UI了,因為handleMessage是在主線程中嘛。到這裡就會有以下疑問了:

  • Handler明明是在子線程中發的消息怎麼會跑到主線程中了呢?
  • Handler的發送消息handleMessage又是怎麼接收到的呢?

帶着這兩個疑問,開始分析Handler的源碼。

Handler的源碼分析

先看下在我們執行個體化Handler的時候,Handler的構造方法中都做了那些事情,看代碼

final Looper mLooper;
 final MessageQueue mQueue;
 final Callback mCallback;
 final boolean mAsynchronous;
/**
 * Default constructor associates this handler with the {@link Looper} for the
 * current thread.
 *
 * If this thread does not have a looper, this handler won't be able to receive messages
 * so an exception is thrown.
 */
 public Handler() {
 this(null, false);
 }
/**
 * Use the {@link Looper} for the current thread with the specified callback interface
 * and set whether the handler should be asynchronous.
 *
 * Handlers are synchronous by default unless this constructor is used to make
 * one that is strictly asynchronous.
 *
 * Asynchronous messages represent interrupts or events that do not require global ordering
 * with respect to synchronous messages. Asynchronous messages are not subject to
 * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
 *
 * @param callback The callback interface in which to handle messages, or null.
 * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
 * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
 *
 * @hide
 */
 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的無參構造函數調用了兩個參數的構造函數,而在兩個參數的構造函數中就是将一些變量進行指派。

看下下面的代碼

mLooper = Looper.myLooper();
 if (mLooper == null) {
 throw new RuntimeException(
 "Can't create handler inside thread that has not called Looper.prepare()");
 }           

這裡是通過Looper中的myLooper方法來獲得Looper執行個體的,如果Looper為null的話就會抛異常,抛出的異常内容翻譯過來就是

無法在未調用Looper.prepare()的線程内建立handler

從這句話中,我們可以知道,在調用Looper.myLooper()之前必須要先調用Looper.prepare()方法,現在來看下prepare方法中的内容,如下

/** 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));
 }           

從上面代碼中可以看到,prepare()方法調用了prepare(boolean quitAllowed)方法,prepare(boolean quitAllowed) 方法中則是執行個體化了一個Looper,然後将Looper設定進sThreadLocal中,到了這裡就有必要了解一下ThreadLocalle。

什麼是ThreadLocal

ThreadLocal 為解決多線程程式的并發問題提供了一種新的思路。使用這個工具類可以很簡潔地編寫出優美的多線程程式。

當使用ThreadLocal 維護變量時,ThreadLocal 為每個使用該變量的線程提供獨立的變量副本,是以每一個線程都可以獨立地改變自己的副本,而不會影響其它線程所對應的副本。

如果看完上面這段話還是搞不明白ThreadLocal有什麼用,那麼可以看下下面代碼運作的結果,相信看下結果你就會明白ThreadLocal有什麼作用了。

public class MainActivity extends AppCompatActivity {
 private static final String TAG = "MainActivity";
 private ThreadLocal<Integer> mThreadLocal = new ThreadLocal<>();
 @SuppressLint("HandlerLeak")
 private Handler mHandler = new Handler(){
 @Override
 public void handleMessage(Message msg) {
 super.handleMessage(msg);
 if (msg.what == 1) {
 Log.d(TAG, "onCreate: "+mThreadLocal.get());
 }
 }
 };
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 mThreadLocal.set(5);
 Thread1 thread1 = new Thread1();
 thread1.start();
 Thread2 thread2 = new Thread2();
 thread2.start();
 Thread3 thread3 = new Thread3();
 thread3.start();
 new Thread(new Runnable() {
 @Override
 public void run() {
 try {
 Thread.sleep(2000);
 mHandler.sendEmptyMessage(1);
 } catch (InterruptedException e) {
 e.printStackTrace();
 }
 }
 }).start();
 }
 class Thread1 extends Thread {
 @Override
 public void run() {
 super.run();
 mThreadLocal.set(1);
 Log.d(TAG, "mThreadLocal1: "+ mThreadLocal.get());
 }
 }
 class Thread2 extends Thread {
 @Override
 public void run() {
 super.run();
 mThreadLocal.set(2);
 Log.d(TAG, "mThreadLocal2: "+ mThreadLocal.get());
 }
 }
 class Thread3 extends Thread {
 @Override
 public void run() {
 super.run();
 mThreadLocal.set(3);
 Log.d(TAG, "mThreadLocal3: "+ mThreadLocal.get());
 }
 }
}           

看下這段代碼運作之後列印的log

可以看到雖然在不同的線程中對同一個mThreadLocal中的值進行了更改,但最後仍可以正确拿到目前線程中mThreadLocal中的值。由此我們可以得出結論ThreadLocal.set方法設定的值是與目前線程進行綁定了的。

知道了ThreadLocal.set方法的作用,則Looper.prepare方法就是将Looper與目前線程進行綁定(目前線程就是調用Looper.prepare方法的線程)。

文章到了這裡我們可以知道以下幾點資訊了

  • 在對Handler進行執行個體化的時候,會對一些變量進行指派。
  • 對Looper進行指派是通過Looper.myLooper方法,但在調用這句代碼之前必須已經調用了Looper.prepare方法。
  • Looper.prepare方法的作用就是将執行個體化的Looper與目前的線程進行綁定。

這裡就又出現了一個問題:在調用Looper.myLooper方法之前必須必須已經調用了Looper.prepare方法,即在執行個體化Handler之前就要調用Looper.prepare方法,但是我們平常在主線程中使用Handler的時候并沒有調用Looper.prepare方法呀!這是怎麼回事呢?

其實,在主線程中Android系統已經幫我們調用了Looper.prepare方法,可以看下ActivityThread類中的main方法,代碼如下

public static void main(String[] args) {
 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
 // 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());
 // Make sure TrustedCertificateStore looks in the right place for CA certificates
 final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
 TrustedCertificateStore.setDefaultUserDirectory(configDir);
 Process.setArgV0("<pre-initialized>");
 Looper.prepareMainLooper();
 ActivityThread thread = new ActivityThread();
 thread.attach(false);
 if (sMainThreadHandler == null) {
 sMainThreadHandler = thread.getHandler();
 }
 if (false) {
 Looper.myLooper().setMessageLogging(new
 LogPrinter(Log.DEBUG, "ActivityThread"));
 }
 // End of event ActivityThreadMain.
 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
 Looper.loop();
 throw new RuntimeException("Main thread loop unexpectedly exited");
 }           

上面的代碼中有一句

Looper.prepareMainLooper();           

這句話的實質就是調用了Looper的prepare方法,代碼如下

public static void prepareMainLooper() {
 prepare(false);//這裡調用了prepare方法
 synchronized (Looper.class) {
 if (sMainLooper != null) {
 throw new IllegalStateException("The main Looper has already been prepared.");
 }
 sMainLooper = myLooper();
 }
 }           

到這裡就解決了,為什麼我們在主線程中使用Handler之前沒有調用Looper.prepare方法的問題了。

讓我們再回到Handler的構造方法中,看下

mLooper = Looper.myLooper();           

myLooper()方法中代碼如下

/**
 * Return the Looper object associated with the current thread. Returns
 * null if the calling thread is not associated with a Looper.
 */
 public static @Nullable Looper myLooper() {
 return sThreadLocal.get();
 }           

其實就是從目前線程中的ThreadLocal中取出Looper執行個體。

再看下Handler的構造方法中的

mQueue = mLooper.mQueue;           

這句代碼。這句代碼就是拿到Looper中的mQueue這個成員變量,然後再指派給Handler中的mQueue,下面看下Looper中的代碼

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

同過上面的代碼,我們可以知道mQueue就是MessageQueue,在我們調用Looper.prepare方法時就将mQueue執行個體化了。

Handler的sendMessage方法都做了什麼

還記得文章開始時的兩個問題嗎?

下面就分析一下Handler的sendMessage方法都做了什麼,看代碼

public final boolean sendMessage(Message msg)
 {
 return sendMessageDelayed(msg, 0);
 }
public final boolean sendMessageDelayed(Message msg, long delayMillis)
 {
 if (delayMillis < 0) {
 delayMillis = 0;
 }
 return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
 }
/**
 * Enqueue a message into the message queue after all pending messages
 * before the absolute time (in milliseconds) <var>uptimeMillis</var>.
 * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
 * Time spent in deep sleep will add an additional delay to execution.
 * You will receive it in {@link #handleMessage}, in the thread attached
 * to this handler.
 * 
 * @param uptimeMillis The absolute time at which the message should be
 * delivered, using the
 * {@link android.os.SystemClock#uptimeMillis} time-base.
 * 
 * @return Returns true if the message was successfully placed in to the 
 * message queue. Returns false on failure, usually because the
 * looper processing the message queue is exiting. Note that a
 * result of true does not mean the message will be processed -- if
 * the looper is quit before the delivery time of the message
 * occurs then the message will be dropped.
 */
 public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
 MessageQueue queue = mQueue;
 if (queue == null) {
 RuntimeException e = new RuntimeException(
 this + " sendMessageAtTime() called with no mQueue");
 Log.w("Looper", e.getMessage(), e);
 return false;
 }
 return enqueueMessage(queue, msg, uptimeMillis);
 }           

由上面的代碼可以看出,Handler的sendMessage方法最後調用了sendMessageAtTime這個方法,其實,無論時sendMessage、sendEmptyMessage等方法最終都是調用sendMessageAtTime。可以看到sendMessageAtTime這個方法最後傳回的是enqueueMessage(queue, msg, uptimeMillis);下面看下這個方法,代碼如下

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

這裡有一句代碼非常重要。

msg.target = this;           

這句代碼就是将目前的Handler指派給了Message中的target變量。這樣,就将每個調用sendMessage方法的Handler與Message進行了綁定。

enqueueMessage方法最後傳回的是queue.enqueueMessage(msg, uptimeMillis);也就是調用了MessageQueue中的enqueueMessage方法,下面看下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;
 }           

上面的代碼就是将消息放進消息隊列中,如果消息已成功放入消息隊列,則傳回true。失敗時傳回false,而失敗的原因通常是因為處理消息隊列正在退出。代碼分析到這裡可以得出以下兩點結論了

Handler在sendMessage時會将自己設定給Message的target變量即将自己與發送的消息綁定。

Handler的sendMessage是将Message放入MessageQueue中。

到了這裡已經知道Handler的sendMessage是将消息放進MessageQueue中,那麼又是怎樣從MessageQueue中拿到消息的呢?想要知道答案請繼續閱讀。

怎樣從MessageQueue中擷取Message

在文章的前面,貼出了ActivityThread類中的main方法的代碼,不知道細心的你有沒有注意到,在main方法的結尾處調用了一句代碼

Looper.loop();           

好了,現在可以看看Looper.loop();這句代碼到底做了什麼了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();//通過myLooper方法拿到與主線程綁定的Looper
 if (me == null) {
 throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
 }
 final MessageQueue queue = me.mQueue;//從Looper中得到MessageQueue
 // 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);           

執行到這句代碼,說明已經從消息隊列中拿到了消息,還記得msg.target嗎?就是Message中的target變量呀!也就是發送消息的那個Handler,是以這句代碼的本質就是調用了Handler中的dispatchMessage(msg)方法,代碼分析到這裡是不是有點小激動了呢!穩住!下面看下dispatchMessage(msg)這個方法,代碼如下

/**
 * 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);
 }
 }           

現在來一句句的來分析上面的代碼,先看下這句

if (msg.callback != null) {
 handleCallback(msg);
 }            

msg.callback就是Runnable對象,當msg.callback不為null時會調用 handleCallback(msg)方法,先來看下 handleCallback(msg)方法,代碼如下

private static void handleCallback(Message message) {
 message.callback.run();
 }           

上面的代碼就是調用了Runnable的run方法。那什麼情況下if (msg.callback != null)這個條件成立呢!還記得使用Handler的另一種方法嗎?就是調用Handler的post方法呀!這裡說明一下,使用Handler其實是有兩種方法的

使用Handler的sendMessage方法,最後在handleMessage(Message msg)方法中來處理消息。

使用Handler的post方法,最後在Runnable的run方法中來處理,代碼如下

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
 private Button mTimeCycle,mStopCycle;
 private Runnable mRunnable;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 initView();
 }
 private void initView() {
 mTimeCycle = findViewById(R.id.btn_time_cycle);
 mTimeCycle.setOnClickListener(this);
 mStopCycle = findViewById(R.id.btn_stop_cycle);
 mStopCycle.setOnClickListener(this);
 mRunnable = new Runnable() {
 @Override
 public void run() {
 Toast.makeText(MainActivity.this, "正在循環!!!", Toast.LENGTH_SHORT).show();
 mHandler.postDelayed(mRunnable, 1000);
 }
 };
 }
 @Override
 public void onClick(View v) {
 switch (v.getId()) {
 case R.id.btn_time_cycle:
 mHandler.post(mRunnable);
 break;
 case R.id.btn_stop_cycle:
 mHandler.removeCallbacks(mRunnable);
 break;
 }
 }
}           

第一種方法,我們已經分析了,下面來分析一下第二種使用方式的原理,先看下Handler的post的方法做了什麼,代碼如下

/**
 * Causes the Runnable r to be added to the message queue.
 * The runnable will be run on the thread to which this handler is 
 * attached. 
 * 
 * @param r The Runnable that will be executed.
 * 
 * @return Returns true if the Runnable was successfully placed in to the 
 * message queue. Returns false on failure, usually because the
 * looper processing the message queue is exiting.
 */
 public final boolean post(Runnable r)
 {
 return sendMessageDelayed(getPostMessage(r), 0);
 }
 private static Message getPostMessage(Runnable r) {
 Message m = Message.obtain();
 m.callback = r;
 return m;
 }           

由上面的代碼不難看出,post方法最終也是将Runnable封裝成消息,然後将消息放進MessageQueue中。下面繼續分析dispatchMessage方法中的代碼

else {
 //if中的代碼其實是和if (msg.callback != null) {handleCallback(msg);} 
 //原理差不多的,隻不過mCallback是Handler中的成員變量。
 if (mCallback != null) {
 if (mCallback.handleMessage(msg)) {
 return;
 }
 }
 //當上面的條件都不成立時,就會調用這句代碼
 handleMessage(msg);
 }
上面的代碼就不分析了,我已經在代碼中進行了注釋,下面再看下handleMessage(msg)這個方法,代碼如下

/**
 * Subclasses must implement this to receive messages.
 */
 public void handleMessage(Message msg) {
 }           

其實,他就是一個空方法,具體的代碼讓我們自己重寫這個方法進行處理。代碼分析到這裡,已經可以給出下面問題的答案了。

在子線程中Handler在發送消息的時候已經把自己與目前的message進行了綁定,在通過Looper.loop()開啟輪詢message的時候,當獲得message的時候會調用 與之綁定的Handler的handleMessage(Message msg)方法,由于Handler是在主線程建立的,是以自然就由子線程切換到了主線程。

總結

上面已經嗯将Handler的源碼分析了一遍,現在來進行一些總結:

1、Handler的工作原理

在使用Handler之前必須要調用Looper.prepare()這句代碼,這句代碼的作用是将Looper與目前的線程進行綁定,在執行個體化Handler的時候,通過Looper.myLooper()擷取Looper,然後再獲得Looper中的MessageQueue。

在子線程中調用Handler的sendMessage方法就是将Message放入MessageQueue中,然後調用Looper.loop()方法來從MessageQueue中取出Message,在取到Message的時候,執行 msg.target.dispatchMessage(msg);這句代碼,這句代碼就是從目前的Message中取出Handler然後執行Handler的handleMessage方法。

2、Handler、Message、MessageQueue以及Looper之間的關系

在介紹它們之間的關系之前,先說一下它們各自的作用。

Handler:負責發送和處理消息。

Message:用來攜帶需要的資料。

MessageQueue:消息隊列,隊列裡面的内容就是Message。

Looper:消息輪巡器,負責不停的從MessageQueue中取Message。

它們的關系如下圖(圖檔來源于網上)

3、在子線程中使用Handler

在子線程中使用Handler的方式如下class LooperThread extends Thread {
 public Handler mHandler;
 public void run() {
 Looper.prepare();
 mHandler = new Handler() {
 public void handleMessage(Message msg) {
 // process incoming messages here
 }
 };
 Looper.loop();
 }
}           

結束語

本文将Handler的機制詳細講解了一遍,包括在面試中有關Handler的一些問題,在文章中也能找到答案。

順便說下閱讀代碼應該注意的地方,在分析源碼之前應該知道你分析代碼的目的,就是你為了得到什麼答案而分析代碼;在分析代碼時切記要避輕就重,不要想着要搞懂每句代碼做了什麼,要找準大方向。文中的代碼已上傳到GitHub,可以在這裡擷取,與Handler有關的源碼在我上傳的源碼的handler包中。

本文轉載自:www.wizardev.com

學習分享,共勉

題外話,我從事Android開發已經五年了,此前我指導過不少同行。但很少跟大家一起探讨,正好最近我花了三個多月的時間整理出來一份包括全套Android面試精編大全+Android面試視訊解析,今天暫且開放給有需要的人,若有關于此方面可以轉發+關注+點贊,點選

面試

,前往免費領取!

繼續閱讀