自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Android消息機(jī)制Handler,有必要再講一次

移動開發(fā) Android
我們在日常開發(fā)中,總是不可避免的會用到 Handler,雖說 Handler 機(jī)制并不等同于 Android 的消息機(jī)制,但 Handler 的消息機(jī)制在 Android 開發(fā)中早已諳熟于心,非常重要!

我們在日常開發(fā)中,總是不可避免的會用到 Handler,雖說 Handler 機(jī)制并不等同于 Android 的消息機(jī)制,但 Handler 的消息機(jī)制在 Android 開發(fā)中早已諳熟于心,非常重要!

[[271774]]

通過本文,你可以非常容易得到一下問題的答案:

  1. Handler、Looper、Message 和 MessageQueue 的原理以及它們之間的關(guān)系到底是怎樣的?
  2. MessageQueue 存儲結(jié)構(gòu)是什么?
  3. 子線程為啥一定要調(diào)用 Looper.prepare() 和 Looper.loop()?

Handler 的簡單使用

相信應(yīng)該沒有人不會使用 Handler 吧?假設(shè)在 Activity 中處理一個耗時任務(wù),需要更新 UI,簡單看看我們平時是怎么處理的。

  1. override fun onCreate(savedInstanceState: Bundle?) { 
  2.  super.onCreate(savedInstanceState) 
  3.  setContentView(R.layout.activity_main3) 
  4.  // 請求網(wǎng)絡(luò) 
  5.  subThread.start() 
  6. override fun onDestroy() { 
  7.  subThread.interrupt() 
  8.  super.onDestroy() 
  9. private val handler by lazy(LazyThreadSafetyMode.NONE) { MyHandler() } 
  10. private val subThread by lazy(LazyThreadSafetyMode.NONE) { SubThread(handler) } 
  11. private class MyHandler : Handler() { 
  12.  override fun handleMessage(msg: Message) { 
  13.  super.handleMessage(msg) 
  14.  // 主線程處理邏輯,一般這里需要使用弱引用持有 Activity 實(shí)例,以免內(nèi)存泄漏 
  15.  } 
  16. private class SubThread(val handler: Handler) : Thread() { 
  17.  override fun run() { 
  18.  super.run() 
  19.  // 耗時操作 比如做網(wǎng)絡(luò)請求 
  20.  // 網(wǎng)絡(luò)請求完畢,咱們就得嘩嘩嘩通知 UI 刷新了,直接直接考慮 Handler 處理,其他方案暫時不做考慮 
  21.  // 第一種方法,一般這個 data 是請求結(jié)果解析的內(nèi)容 
  22.  handler.obtainMessage(1,data).sendToTarget() 
  23.  // 第二種方法 
  24.  val message = Message.obtain() // 盡量使用 Message.obtain() 初始化 
  25.  message.what = 1 
  26.  message.obj = data // 一般這個 data 是請求結(jié)果解析的內(nèi)容 
  27.  handler.sendMessage(message) 
  28.  // 第三種方法 
  29.  handler.post(object : Thread() { 
  30.  override fun run() { 
  31.  super.run() 
  32.  // 處理更新操作 
  33.  } 
  34.  }) 
  35.  } 

上述代碼非常簡單,因?yàn)榫W(wǎng)絡(luò)請求是一個耗時任務(wù),所以我們新開了一個線程,并在網(wǎng)絡(luò)請求結(jié)束解析完畢后通過 Handler 來通知主線程去更新 UI,簡單采用了 3 種方式,細(xì)心的小伙伴可能會發(fā)現(xiàn),其實(shí)第一種和第二種方法是一樣的。就是利用 Handler 來發(fā)送了一個攜帶了內(nèi)容 Message 對象,值得一提的是:我們應(yīng)該盡可能地使用 Message.obtain() 而不是 new Message() 進(jìn)行 Message 的初始化,主要是 Message.obtain() 可以減少內(nèi)存的申請。

受到大家在前面文章提出的建議,我們就盡量地少貼一些源碼了,大家可以直接很容易發(fā)現(xiàn),上述的所有方法最終都會調(diào)用這個方法:

  1. public boolean sendMessageAtTime(Message msg, long uptimeMillis) { 
  2.  MessageQueue queue = mQueue; 
  3.  if (queue == null) { 
  4.  RuntimeException e = new RuntimeException( 
  5.  this + " sendMessageAtTime() called with no mQueue"); 
  6.  Log.w("Looper", e.getMessage(), e); 
  7.  return false
  8.  } 
  9.  return enqueueMessage(queue, msg, uptimeMillis); 
  10. private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { 
  11.  msg.target = this; 
  12.  if (mAsynchronous) { 
  13.  msg.setAsynchronous(true); 
  14.  } 
  15.  return queue.enqueueMessage(msg, uptimeMillis); 

上面的代碼出現(xiàn)了一個 MessageQueue,并且最終調(diào)用了 MessageQueue#enqueueMessage 方法進(jìn)行消息的入隊,我們不得不簡單說一下 MessageQueue 的基本情況。

MessageQueue

顧名思義,MessageQueue 就是消息隊列,即存放多條消息 Message 的容器,它采用的是單向鏈表數(shù)據(jù)結(jié)構(gòu),而非隊列。它的 next() 指向鏈表的下一個 Message 元素。

  1. boolean enqueueMessage(Message msg, long when) { 
  2.  // ... 省略一些檢查代碼 
  3.  synchronized (this) { 
  4.  // ... 省略一些檢查代碼 
  5.  msg.markInUse(); 
  6.  msg.when = when
  7.  Message p = mMessages; 
  8.  boolean needWake; 
  9.  if (p == null || when == 0 || when < p.when) { 
  10.  // New head, wake up the event queue if blocked. 
  11.  msg.next = p; 
  12.  mMessages = msg; 
  13.  needWake = mBlocked; 
  14.  } else { 
  15.  // Inserted within the middle of the queue. Usually we don't have to wake 
  16.  // up the event queue unless there is a barrier at the head of the queue 
  17.  // and the message is the earliest asynchronous message in the queue. 
  18.  needWake = mBlocked && p.target == null && msg.isAsynchronous(); 
  19.  Message prev; 
  20.  for (;;) { 
  21.  prev = p; 
  22.  p = p.next
  23.  if (p == null || when < p.when) { 
  24.  break; 
  25.  } 
  26.  if (needWake && p.isAsynchronous()) { 
  27.  needWake = false
  28.  } 
  29.  } 
  30.  msg.next = p; // invariant: p == prev.next 
  31.  prev.next = msg; 
  32.  } 
  33.  // We can assume mPtr != 0 because mQuitting is false
  34.  if (needWake) { 
  35.  nativeWake(mPtr); 
  36.  } 
  37.  } 
  38.  return true

從入隊消息 enqueueMessage() 的實(shí)現(xiàn)來看,它的主要操作其實(shí)就是單鏈表的插入操作,這里就不做過多的解釋了,我們可能應(yīng)該更多的關(guān)心它的出隊操作方法 next():

  1. Message next() { 
  2.  // ... 
  3.  int nextPollTimeoutMillis = 0; 
  4.  for (;;) { 
  5.  // ... 
  6.  nativePollOnce(ptr, nextPollTimeoutMillis); 
  7.  synchronized (this) { 
  8.  // Try to retrieve the next message. Return if found. 
  9.  final long now = SystemClock.uptimeMillis(); 
  10.  Message prevMsg = null
  11.  Message msg = mMessages; 
  12.  if (msg != null && msg.target == null) { 
  13.  // Stalled by a barrier. Find the next asynchronous message in the queue. 
  14.  do { 
  15.  prevMsg = msg; 
  16.  msg = msg.next
  17.  } while (msg != null && !msg.isAsynchronous()); 
  18.  } 
  19.  if (msg != null) { 
  20.  if (now < msg.when) { 
  21.  // Next message is not ready. Set a timeout to wake up when it is ready. 
  22.  nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE); 
  23.  } else { 
  24.  // Got a message. 
  25.  mBlocked = false
  26.  if (prevMsg != null) { 
  27.  prevMsg.next = msg.next
  28.  } else { 
  29.  mMessages = msg.next
  30.  } 
  31.  msg.next = null
  32.  if (DEBUG) Log.v(TAG, "Returning message: " + msg); 
  33.  msg.markInUse(); 
  34.  return msg; 
  35.  } 
  36.  } else { 
  37.  // No more messages. 
  38.  nextPollTimeoutMillis = -1; 
  39.  } 
  40.  //... 
  41.  } 
  42.  //... 
  43.  // While calling an idle handler, a new message could have been delivered 
  44.  // so go back and look again for a pending message without waiting. 
  45.  nextPollTimeoutMillis = 0; 
  46.  } 

next() 方法其實(shí)很長,不過我們僅僅貼了極少的一部分,可以看到,里面不過是有一個 for (;;) 的無限循環(huán),循環(huán)體內(nèi)部調(diào)用了一個 nativePollOnce(long, int) 方法。這是一個 Native 方法,實(shí)際作用是通過 Native 層的 MessageQueue 阻塞當(dāng)前調(diào)用棧線程 nextPollTimeoutMillis 毫秒的時間。

下面是 nextPollTimeoutMillis 取值的不同情況的阻塞表現(xiàn):

  • 小于 0,一直阻塞,直到被喚醒;
  • 等于 0,不會阻塞;
  • 大于 0,最長阻塞 nextPollTimeoutMillis 毫秒,期間如被喚醒會立即返回。

可以看到,最開始 nextPollTimeoutMillis 的初始化值是 0,所以不會阻塞,會直接去取 Message 對象,如果沒有取到 Message 對象數(shù)據(jù),則直接會把 nextPollTimeoutMillis 置為 -1,此時滿足小于 0 的條件,會被一直阻塞,直到其他地方調(diào)用另外一個 Native 方法 nativeWake(long) 進(jìn)行喚醒。如果取到值的話,會直接把得到的 Message 對象進(jìn)行返回。

原來,nativeWake(long) 方法在前面的 MessageQueue#enqueueMessage 方法有個調(diào)用,調(diào)用時機(jī)是在 MessageQueue 入隊消息的過程中。

現(xiàn)在已經(jīng)知道:Handler 發(fā)送了 Message,消息用 MessageQueue 進(jìn)行存儲,使用 MessageQueue#enqueueMessage 方法進(jìn)行入隊,使用 MessageQueue#next 方法進(jìn)行輪訓(xùn)消息。這就不免拋出了一個問題,MessageQueue#next 方法是誰調(diào)用的?沒錯,就是 Looper。

Looper

Looper 在 Android 的消息機(jī)制中扮演著消息循環(huán)的角色,具體來說就是它會不停地從 MessageQueue 通過 next() 查看是否有新消息,如果有新消息就立刻處理,否則就任由 MessageQueue 阻塞在那里。

我們直接看看 Looper 最重要的方法:loop():

  1. public static void loop() { 
  2.  final Looper me = myLooper(); 
  3.  if (me == null) { 
  4.  throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); 
  5.  } 
  6.  // ... 
  7.  for (;;) { 
  8.  Message msg = queue.next(); // might block 
  9.  if (msg == null) { 
  10.  // No message indicates that the message queue is quitting. 
  11.  return
  12.  } 
  13.  //... 
  14.  try { 
  15.  // 分發(fā)消息給 handler 處理 
  16.  msg.target.dispatchMessage(msg); 
  17.  dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0; 
  18.  } finally { 
  19.  // ... 
  20.  } 
  21.  // ... 
  22.  } 

方法省去了大量的代碼,只保留了核心邏輯??梢钥吹?,首先會通過 myLooper() 方法得到 Looper 對象,如果這個 Looper 返回為空的話,則直接拋出異常。否則進(jìn)入到一個 for (;;) 循環(huán)中,調(diào)用 MessageQueue#next() 方法進(jìn)行輪訓(xùn)獲取 Message 對象,如果獲取的 Message 對象為空,則直接退出 loop() 方法。否則直接通過 msg.target 拿到 Handler 對象,并調(diào)用 Handler#dispatchMessage() 方法。

我們先來看看Handler#dispatchMessage() 方法實(shí)現(xiàn):

  1. public void dispatchMessage(Message msg) { 
  2.  if (msg.callback != null) { 
  3.  handleCallback(msg); 
  4.  } else { 
  5.  if (mCallback != null) { 
  6.  if (mCallback.handleMessage(msg)) { 
  7.  return
  8.  } 
  9.  } 
  10.  handleMessage(msg); 
  11.  } 
  12. private static void handleCallback(Message message) { 
  13.  message.callback.run(); 

代碼比較簡單,如果 Message 設(shè)置了 callback 則,直接調(diào)用 message.callback.run(),否則判斷是否初始化了 `m

再來看看 myLooper() 方法:

  1. public static @Nullable Looper myLooper() { 
  2.  return sThreadLocal.get(); 

看看 sThreadLocal 是什么:

  1. static final ThreadLocal sThreadLocal = new ThreadLocal(); 

這個 ThreadLocal 是什么呢?

ThreadLocal

關(guān)于 ThreadLocal,我們直接采取 嚴(yán)振杰文章 中的內(nèi)容。

看到 ThreadLocal 的第一感覺就是該類和線程有關(guān),確實(shí)如此,但是要注意它不是線程,否則它就該叫 LocalThread 了。

ThreadLocal 是用來存儲指定線程的數(shù)據(jù)的,當(dāng)某些數(shù)據(jù)的作用域是該指定線程并且該數(shù)據(jù)需要貫穿該線程的所有執(zhí)行過程時就可以使用 ThreadnLocal 存儲數(shù)據(jù),當(dāng)某線程使用 ThreadnLocal 存儲數(shù)據(jù)后,只有該線程可以讀取到存儲的數(shù)據(jù),除此線程之外的其他線程是沒辦法讀取到該數(shù)據(jù)的。

一些讀者看完上面這段話應(yīng)該還是不理解 ThreadLocal 的作用,我們舉個栗子:

  1. ThreadLocal<Boolean> local = new ThreadLocal<>(); 
  2. // 設(shè)置初始值為true
  3. local.set(true); 
  4. Boolean bool = local.get(); 
  5. Logger.i("MainThread讀取的值為:" + bool); 
  6. new Thread() { 
  7.  @Override 
  8.  public void run() { 
  9.  Boolean bool = local.get(); 
  10.  Logger.i("SubThread讀取的值為:" + bool); 
  11.  // 設(shè)置值為false
  12.  local.set(false); 
  13.  } 
  14. }.start(): 
  15. // 主線程睡1秒,確保上方子線程執(zhí)行完畢再執(zhí)行下面的代碼。 
  16. Thread.sleep(1000); 
  17. Boolean newBool = local.get(); 
  18. Logger.i("MainThread讀取的新值為:" + newBool); 

代碼沒什么好說的吧,打印出來的日志,你會看到是這樣的:

  • MainThread讀取的值為:trueSubThread讀取的值為:nullMainThread讀取的值為:true

第一條 Log 無可置疑,因?yàn)樵O(shè)置了值為 true,因?yàn)榇蛴〗Y(jié)果沒什么好說的。對于第二條 Log,根據(jù)上方介紹,某線程使用 ThreadLocal 存儲的數(shù)據(jù),只能被該線程讀取,因此第二條 Log 的結(jié)果是:null。緊接著在子線程中設(shè)置了 ThreadLocal 的值為 false,然后第三條 Log 將被打印,原理同上,子線程中設(shè)置了 ThreadLocal 的值并不影響主線程的數(shù)據(jù),所以打印是 true。

實(shí)驗(yàn)結(jié)果證實(shí):就算是同一個 ThreadLocal 對象,任一線程對其的 set() 和 get() 方法的操作都是相互獨(dú)立互不影響的。

Looper.myLooper()

我們回到 Looper.myLooper():

  1. static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>(); 

我們看看是在哪兒對 sThreadLocal 操作的。

  1. public static void prepare() { 
  2.  prepare(true); 
  3. private static void prepare(boolean quitAllowed) { 
  4.  if (sThreadLocal.get() != null) { 
  5.  throw new RuntimeException("Only one Looper may be created per thread"); 
  6.  } 
  7.  sThreadLocal.set(new Looper(quitAllowed)); 

所以知道了吧,這就是在子線程中使用 Handler 前,必須要調(diào)用 Looper.prepare() 的原因。

可能你會疑問,我在主線程使用的時候,沒有要求 Looper.prepare() 呀。

原來,我們在 ActivityThread 中,有去顯示調(diào)用 Looper.prepareMainLooper():

  1. public static void main(String[] args) { 
  2.  // ... 
  3.  Looper.prepareMainLooper(); 
  4.  // ... 
  5.  if (sMainThreadHandler == null) { 
  6.  sMainThreadHandler = thread.getHandler(); 
  7.  } 
  8.  //... 
  9.  Looper.loop(); 
  10.  // ... 
  11.  } 

我們看看 Looper.prepareMainLooper():

  1. public static void prepareMainLooper() { 
  2.  prepare(false); 
  3.  synchronized (Looper.class) { 
  4.  if (sMainLooper != null) { 
  5.  throw new IllegalStateException("The main Looper has already been prepared."); 
  6.  } 
  7.  sMainLooper = myLooper(); 
  8.  } 

 

責(zé)任編輯:未麗燕 來源: 安卓巴士
相關(guān)推薦

2021-10-25 09:16:27

MySQL分庫分表

2014-05-22 15:41:59

Android消息處理機(jī)制Looper

2014-05-22 15:38:27

Android消息處理機(jī)制Looper

2014-05-22 15:00:16

Android消息處理機(jī)制Looper

2014-05-22 15:04:00

Android消息處理機(jī)制Looper

2014-05-22 15:07:44

Android消息處理機(jī)制Looper

2014-05-22 15:48:50

Android消息處理機(jī)制Looper

2014-05-22 14:57:28

Android消息處理機(jī)制Looper

2014-05-22 15:15:53

Android消息處理機(jī)制Looper

2014-05-22 15:18:25

Android消息處理機(jī)制Looper

2014-05-22 15:33:31

Android消息處理機(jī)制Looper

2014-05-22 15:45:58

Android消息處理機(jī)制Looper

2011-05-31 11:55:00

Android 消息機(jī)制

2018-08-07 14:45:52

編程語言JavaScripthtml

2025-03-10 00:35:00

AndroidIPC管道

2011-06-28 10:41:50

DBA

2020-03-12 09:34:05

Redis數(shù)據(jù)技術(shù)

2013-04-11 12:40:16

Android消息機(jī)制

2022-08-29 18:14:55

MQ數(shù)據(jù)不丟失

2021-12-27 10:08:16

Python編程語言
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號