需要handler消息機制的原因
- 在android中由於UI線程並不是線程安全的,如果有子線程更新UI容易導致數據錯亂,如果UI線程設置爲線程安全的話導致效率低下;
- 而UI線程做耗時操作容易導致ANR發生。所以需要由子線程做耗時操作當子線程需要更新UI時通知主線程更新UI,而線程間的通信就由Handler消息機制完成。
Handler消息機制原理
在主線程創建一個handler的同時創建了looper和MessageQueue,子線程將需要更新UI的信息構建爲message對象,調用入隊方法添加到消息隊列裏,由looper調用loop方法無限循環取出消息並分發給對應的target(handler),由handler調用handlemessage方法處理消息。由此完成了子線程和主線程的通信。
流程圖如下:
文字解釋:
- 創建一個線程(一般是主線程),在線程內創建一個handler,創建handler的時候初始化了looper和MQ。
- 工作線程產生消息後,調用handler的sendMessageAtTime()方法,發送消息。
- MQ調用enqueueMessage方法將消息入隊到MQ中
- Looper調用loop方法不斷循環MQ的下一條消息
- 獲取下一條消息後Handler調用dispatchMessage方法將消息分發給對應的tartget(Handler)
- 由Handler調用handlerMessage方法處理消息。
由於Handler和線程是綁定的,同一進程中,不同線程是可以公用資源的,所以在線程A中創建了handler,線程B可以調用來發送消息,經過上面步驟將線程B的消息分發到線程A處理,線程間的通信完成。
源碼分析
基於Androidsdk28版本。
1、handler的創建(構造函數)
1.1、空構造函數
//空構造,最終調用的是有參構造函數
public Handler() {
this(null, false);
}
1.2、有參構造函數
空構造函數默認採用當前線程的looper,回調方法callback爲null,消息爲同步處理方式。
//可以指定傳入的looper,可以在子線程傳入mainlooper
public Handler(Looper looper) {
this(looper, null, false);
}
public Handler(Callback callback, boolean async) {
//匿名內部類如果不聲明爲static,會警告內存泄漏
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());
}
}
//初始化獲取looper,具體獲取方法見1.2.1
mLooper = Looper.myLooper();
//必須有一個looper,否則拋異常,這也就是爲什麼子線程直接使用handler會拋異常的原因,解決辦法初始化一個looper
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
//初始化MQ,詳細分析見1.2.2
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
1.2.1、Looper與MQ的初始化
looper通過Looper.myLooper()方法獲取。是通過當前線程的threadlocal獲取。
**ThreadLocal:**線程本地存儲區(TLS),每一個線程都有自己的本地存儲區,不同線程間彼此不能訪問彼此的TLS。
public static @Nullable Looper myLooper() {
//通過線程本地存儲區獲取
return sThreadLocal.get();
}
public T get() {
//獲取當前線程
Thread t = Thread.currentThread();
//獲取當前線程爲key值的ThreadLocalMap:以threadlocal爲key,Entry爲value
ThreadLocalMap map = getMap(t);
if (map != null) {
//獲取當前線程存儲區中的數據
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
一般線程的looper的初始化是在調用Looper.prepare()裏初始化looper並初始化MQ。**注:**主線程的looper及MQ的初始化是在創建主線程的時候由ActivityThread的prepareMainLooper()
方法自動初始化的。
//調用的方法
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
//一個線程只允許有一個looper
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
//創建looper並將looper存儲到當前線程爲key的線程本地存儲區裏 Threadlocal中
sThreadLocal.set(new Looper(quitAllowed)); //new looper的同時初始化了MQ
}
主線程的looper的初始化,主線程不允許退出looper。
public static void prepareMainLooper() {
prepare(false); //設置不允許退出的Looper
synchronized (Looper.class) {
//將當前的Looper保存爲主Looper,每個線程只允許執行一次。
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
Threadlocal的存儲方法:
public void set(T value) {
//獲取當前線程
Thread t = Thread.currentThread();
//獲取當前線程爲key值的ThreadlocalMap中
ThreadLocalMap map = getMap(t);
//如果已經存在,替換value
if (map != null)
map.set(this, value);
else
//不存在,創建map
createMap(t, value);
}
MessageQueue的初始化:
private Looper(boolean quitAllowed) {
//初始化MQ
mQueue = new MessageQueue(quitAllowed);
//將looper綁定爲當前線程
mThread = Thread.currentThread();
}
2、Handler的發送消息
2.1、handler發送消息
在工作線程中構建一個Message對象,調用handler的sentXXX進行發送消息,幾個sentXXX方法最終都是調用sendMessageAtTime(Message msg, long uptimeMillis);將消息放入一個消息隊列。
//獲取到消息隊列,並將發送的消息按時間入列,消息隊列在loop的構造方法中創建
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;
}
//指定msg的target爲handler並將消息入列
return enqueueMessage(queue, msg, uptimeMillis);
}
//sendMessageAtFrontOfQueue 設置消息觸發時間爲0達到將消息放在隊列頭的目的
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
//指定了msg的target是handler
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
//調用MQ的入列操作
return queue.enqueueMessage(msg, uptimeMillis);
}
MQ的消息入列操作:注:MQ的存儲結構不是隊列,而是單鏈表。
boolean enqueueMessage(Message msg, long when) {
//msg必須有一個分發的目標
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) {
//MQ中沒有消息,或者當前待處理消息的時間是最早的
// 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;
//將消息按時間順序插入到MQ中
for (;;) {
prev = p;
p = p.next;
//無當前處理消息,或者傳進來的消息時間比當前處理消息時間早跳出循環
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
//將當前消息放在P(待處理消息)前
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;
}
3、輪詢取出消息
3.1、loop方法
- 獲取looper
- 不斷的讀取MQ裏的下一條消息(沒有消息時跳出死循環)
- 將消息分發給相應的target
- 把分發後的消息回收到消息池。
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
public static void loop() {
//獲取looper
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 (;;) {
//讀取MQ裏的下一條消息
Message msg = queue.next(); // might block
//沒有消息的時候跳出死循環
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
// ....省略....
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 即Handler進行分發事件
msg.target.dispatchMessage(msg);
end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
}
//...省略...
//確保事件分發中identity不會被損壞
final long newIdent = Binder.clearCallingIdentity();
//...省略...
msg.recycleUnchecked(); //將消息放入消息池以便重複利用。
}
3.2、讀取下一條消息
Message next() {
//當looper已經退出時,直接返回,這種情況出現在App試圖在退出後重啓looper,這是不允許的
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();
}
//阻塞操作,在native層完成
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) {
// 當target爲null 時,查找下一條消息
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
// 當前時間比消息觸發時間短,重新設置下一次輪詢的超時時長
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.
//當消息是消息隊列的第一個消息或者MQ爲null時執行Idle handle
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;
}
}
3.3、循環獲取到消息後分發給target----dispatchMessage
public void dispatchMessage(Message msg) {
//msg回調方法不爲null ,調用 message.callback.run();
if (msg.callback != null) {
handleCallback(msg);
} else {
//當Handler成員mCallback 不爲null時,調用成員變量的callback handleMessage
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
//否則調用Handler的自身的handleMessage方法。
handleMessage(msg);
}
}
消息分發的優先級:
- Message的回調方法:
message.callback.run()
,優先級最高。 - Handler的回調方法:
Handler.mCallback.handleMessage(msg)
- Handler的默認方法:
Handler.handleMessage(msg);
問題:
1、 Handler
,Looper
,Message
,MessageQueue
,Thread
的對應關係?
- Handler:主要發送消息(Handler.sentMessage())和處理消息(Handler.handleMessage())。Handler中有Looper和MessageQueue。
- Looper:循環執行(Looper.loop()),按分發機制將消息分發給目標處理者。Looper中有一個MessageQueue.
- Message:消息分爲硬件(按鈕、觸摸)或軟件生成的消息。Message中有一個Handler。
- MessageQueue:消息隊列主要功能是入隊(MessageQueue.enqueueMessage())消息和取出(MessageQueue.next())消息。消息隊列中有一組Message(待處理消息)。
- Thread:線程,主要 是處理事務,一個Thread綁定一個Looper
2、主線程向子線程發消息如何發?
在子線程創建Handler,同時需要創建Looper,發送消息,在子線程中獲取消息並處理消息。
3、在子線程 new 一個 Handler
需要注意什麼?
在子線程中直接創建Handler會導致程序崩潰,報錯:Can’t create handler inside thread that has not called Looper.prepare()。 需要手動創建一個looper。
4、Looper 死循環爲什麼不會導致應用卡死,會消耗大量資源嗎?**
- 當子線程運行結束時,線程退出,線程生命週期結束,(通過查看next方法,子線程開的looper對象的是否允許退出是true,所以在子線程執行next時循環到沒有消息時,會執行dispose進行清理工作。)
- 而對於主線程,我們不希望可運行期間退出,所以死循環保證了線程不被退出,當沒有消息時,會通過nativePollOnce進行阻塞。
- 主線程死循環不會消耗大量的資源,因爲在主線程的MessageQueue沒有消息時,便阻塞在loop()的next()裏的nativePollOnce()方法裏。此時主線程會釋放CPU資源進入休眠狀態,直到下個消息入隊到消息隊列,通過往管道寫入字符喚醒loop線程(主線程)。
5、主線程的消息循環機制是什麼(死循環如何處理其它事務)?
-
主線程死循環 通過創建新線程處理其他事務。
-
主線程的消息循環模型:AT(ActivityThread)通過ApplicationThread和AMS(ActivityManagerService)進行進程間通信。AMS完成AT的請求後會回調ApplicationThread中的Binder方法,ApplicationThread會向H發送消息,H接收到消息後會將ApplicationThread中的邏輯切換到AT中執行。
6、ActivityThread 的動力是什麼?(ATLooper中綁定的線程是什麼?)
AT沒有集成Thread,不是一個線程,那麼在AT中Looper綁定的線程是zygote fork出來的進程,進程與線程的區別可能只是是否可以資源共享。
7、Handler如何能夠切換線程?
同一進程間線程資源是共享的,Handler綁定的是在它關聯的Looper綁定的線程處理消息的。
8、子線程有哪些更新UI的方法?
- 主線程定義Handler,子線程發送消息,主線程更新UI。
- runOnMainThread
- 創建Handler,傳入getMainLooper
- View.Post(Runable r);
Handler綁定的是在它關聯的Looper綁定的線程處理消息的,幾種方法的源碼歸根結低都是使用Handler消息機制。
9、如何避免Handler造成的內存泄漏?
在子線程中如果創建Looper,那麼在所有的事情完成後如果不將looper調用quit方法退出,子線程會一直等待,如果Looper退出,線程也就退出了。
另外如果在主線程Handler處理消息是有一個延時消息,會一直保存在 主線程的消息隊列裏,會影響系統對Activity的回收。
所以避免內存泄漏:
- 在確定子線程不需要looper時將其退出。
- 有延時消息時在Activity銷燬時將Message移除。
- 非靜態內部類和匿名內部類會隱式持有外部類的引用,handler不被釋放,持有的外部類也不能被釋放,匿名內部類改成匿名靜態內部類(一開始創建內存),對Activity的引用使用弱引用。
解決Handler內存泄漏例子如下:
1、內存泄漏的例子:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
//創建handler----非靜態內部類
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//模擬異步操作
handler.postDelayed(new Runnable() {
@Override
public void run() {
Log.d(TAG, "run: 模擬異步操作");
}
},1000*60*5);
}
}
2、檢測內存泄漏-Android profiler
- 運行項目,點擊Android profiler,選擇設備及報名,選擇MEMORY項查看內存。
- 選擇app package(Arrange by package) ,點擊旁邊 Jump Java heap按鈕查看堆棧信息,在左邊看到引用樹。
- 反覆關閉頁面操作,觀察引用樹,MainActivity一直未被回收,此時已經發生內存泄漏。
- 點擊左上角的垃圾桶(GC)內存也沒有明顯變化。
兩個實例的depth都是3,不可以被GC,引用樹裏Reference有massage相關的,大概就是Handler發生了內存泄漏。
2.1、檢測內存泄漏-LeakCanary
-
添加依賴
//內存泄漏檢測 debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.6.1' releaseImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.6.1' // Optional, if you use support library fragments: debugImplementation 'com.squareup.leakcanary:leakcanary-support-fragment:1.6.1'
-
在Application中安裝LeakCanary
if (LeakCanary.isInAnalyzerProcess(this)){ return; } LeakCanary.install(this);
如果可能發生內存泄漏時會通知引用樹。查看最後的引用情況就是MessageQueue.mMessages.
3、修復內存泄漏
**分析:**在Java中非靜態內部類或匿名內部類會隱式持有外部類實例。修改爲靜態內部類和弱引用持有外部類。
//修改爲靜態內部類
private static class MyHandler extends Handler{
private final WeakReference<MainActivity> mActivity;
public MyHandler(MainActivity activity) {
mActivity = new WeakReference<>(activity);
}
@Override
public void handleMessage(Message msg) {
MainActivity mainActivity = mActivity.get();
super.handleMessage(msg);
if (mainActivity!=null){
Log.d(TAG, "handleMessage: 處理邏輯");
}
}
}
private static final Runnable mRunable = new Runnable() {
@Override
public void run() {
Log.d(TAG, "run: 模擬耗時操作");
}
};
private final MyHandler handler = new MyHandler(MainActivity.this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//模擬異步操作
// handler.postDelayed(new Runnable() {
// @Override
// public void run() {
// Log.d(TAG, "run: 模擬異步操作");
// }
// },1000*60*5);
handler.postDelayed(mRunable,1000*60*5);
}
@Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(mRunable);
handler.removeCallbacksAndMessages(null);
// handler.removeMessages();
}
再次使用Android profiler 查看內存,每次頁面關閉時都會觸發GC,內存有明顯變化。
LeakCanary也沒有內存泄漏的通知。
感謝前輩們的分享鏈接:
http://gityuan.com/2015/12/26/handler-message-framework/
http://www.10tiao.com/html/227/201711/2650241824/1.html