【Android 异步操作】Handler 机制 ( Handler 常用用法 | HandlerThread 简介 | HandlerThread 源码注释分析 )
文章目錄
- 一、Handler 常用用法
- 二、HandlerThread 簡介
- 三、HandlerThread 源碼
一、Handler 常用用法
主線程 Handler 主要作用 : Looper 和 Message 都在 主線程 , Handler 也在 主線程 初始化 , 在子線程中調用該 Handler , 通知主線程進行一些操作 , 一般是更新 UI ;
子線程 Handler 主要作用 : Looper 和 Message 都在 子線程 , Handler 也在 子線程 初始化 , 在主線程中調用該 Handler , 通知子線程進行一些操作 , 一般是網絡操作 , 計算 , 或其它耗時任務 ;
二、HandlerThread 簡介
HandlerThread 就是使用了 Handler 機制的線程 , 其本質是一個 線程 Thread ; 屬于上述介紹的 子線程 Handler 機制 ;
在運行 HandlerThread 線程的 run 方法時 ,
在 run 方法開始處 , 會調用 Looper.prepare() 方法 , 初始化該線程的 Looper ,
在 run 方法結束處 , 會調用 Looper.loop() 方法 , 開啟無限循環 , 從 Looper 中的 MessageQueue 中循環獲取消息 , 并轉發給 取出的 Message 消息對應的 Handler 進行相關任務處理 ;
HandlerThread 線程的 run() 方法如下 :
public class HandlerThread extends Thread {@Overridepublic void run() {mTid = Process.myTid();Looper.prepare();synchronized (this) {mLooper = Looper.myLooper();notifyAll();}Process.setThreadPriority(mPriority);onLooperPrepared();Looper.loop();mTid = -1;} }三、HandlerThread 源碼
/*** 含有 Looper 的線程.* Looper 用于創建 Handler.* <p>* 該類是一個線程類, 必須調用 start 方法開啟線程. */ public class HandlerThread extends Thread {int mPriority;int mTid = -1;Looper mLooper;private @Nullable Handler mHandler;public HandlerThread(String name) {super(name);mPriority = Process.THREAD_PRIORITY_DEFAULT;}/*** 創建 HandlerThread.* @param name* @param priority 線程運行優先級*/public HandlerThread(String name, int priority) {super(name);mPriority = priority;}/*** Looper 無限循環之前執行的操作 */protected void onLooperPrepared() {}@Overridepublic void run() {mTid = Process.myTid();// Looper 初始化 Looper.prepare();synchronized (this) {mLooper = Looper.myLooper();notifyAll();}Process.setThreadPriority(mPriority);onLooperPrepared();// 無限循環獲取消息并執行Looper.loop();mTid = -1;}/*** 返回與該線程關聯的 Looper .* 如果線程沒有啟動 , 或者線程不處于活動狀態 , 返回空.* 如果線程已經啟動 , 該方法會阻塞 , 直到 Looper 被初始化完畢后 , 返回 Looper.* @return The looper.*/public Looper getLooper() {if (!isAlive()) {return null;}// If the thread has been started, wait until the looper has been created.synchronized (this) {while (isAlive() && mLooper == null) {try {wait();} catch (InterruptedException e) {}}}return mLooper;}/*** @return 返回一個與該線程關聯的共享 Handler* @hide*/@NonNullpublic Handler getThreadHandler() {if (mHandler == null) {mHandler = new Handler(getLooper());}return mHandler;}/*** 退出 Looper 循環. * <p>* Causes the handler thread's looper to terminate without processing any* more messages in the message queue.* </p><p>* Any attempt to post messages to the queue after the looper is asked to quit will fail.* For example, the {@link Handler#sendMessage(Message)} method will return false.* </p><p class="note">* Using this method may be unsafe because some messages may not be delivered* before the looper terminates. Consider using {@link #quitSafely} instead to ensure* that all pending work is completed in an orderly manner.* </p>** @return True if the looper looper has been asked to quit or false if the* thread had not yet started running.** @see #quitSafely*/public boolean quit() {Looper looper = getLooper();if (looper != null) {looper.quit();return true;}return false;}/*** 安全退出線程 loop.* <p>* Causes the handler thread's looper to terminate as soon as all remaining messages* in the message queue that are already due to be delivered have been handled.* Pending delayed messages with due times in the future will not be delivered.* </p><p>* Any attempt to post messages to the queue after the looper is asked to quit will fail.* For example, the {@link Handler#sendMessage(Message)} method will return false.* </p><p>* If the thread has not been started or has finished (that is if* {@link #getLooper} returns null), then false is returned.* Otherwise the looper is asked to quit and true is returned.* </p>** @return True if the looper looper has been asked to quit or false if the* thread had not yet started running.*/public boolean quitSafely() {Looper looper = getLooper();if (looper != null) {looper.quitSafely();return true;}return false;}/*** 返回線程 ID*/public int getThreadId() {return mTid;} }
總結
以上是生活随笔為你收集整理的【Android 异步操作】Handler 机制 ( Handler 常用用法 | HandlerThread 简介 | HandlerThread 源码注释分析 )的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Android 异步操作】Handle
- 下一篇: 【Android 异步操作】Handle