-
handler用法
post(Runnable)
postDelayed(Runnable, long)
得到message: handler.obtainMessage();
message.sendToTarget()
handler.removeCallbacks(runnable);
攔截消息
查看全部 -
創建一個handler時,默認與一個線程進行綁定,默認線程里面有一個消息隊列
查看全部 -
為什么要用handler
android在設計開發的時候,就封裝了一套消息創建,傳遞,處理機制,如果不遵循這樣的機制,就沒有辦法更新ui信息,就會拋出異常
查看全部 -
handler是什么
handler是android給我們提供用來更新ui的一套機制,也是一套消息處理機制,我們可以發送消息,也可以通過它來處理消息
兩個作用
更新ui
封裝了一套消息處理機制
查看全部 -
使用Handler時必須要關聯一個Looper對象,否則就會回拋出"Can't create handler inside thread that has not called Looper.perpare()"
查看全部 -
在Activity的ViewRootImpl沒有被創建之前是可以在子線程中更新UI的。
因為檢查更新UI的邏輯是否是在主線程中是在ViewRootImpl中進行檢查的。
而ViewRootImpl對象的創建時在Activity.onResume() 方法中被創建的。
所以在ViewRootImpl對象沒有被創建之前是可以在子線程中更新UI的。
但是強烈建議不要在子線程中更新UI,因為不能絕對保證在子線程中更新UI是ViewRootImpl對象沒有被創建
查看全部 -
View.post(Runnable action) 源碼解析:
View的成員變量AttachInfo 不為null.則通過AttachInfo中的Handle.post(action)發送消息
如果View的AttachInfo為null則通過ViewRootImpl.getRunQueue().post(action)發送消息
查看全部 -
runOnUiThread(Runnable action)方法源碼解析
判斷是否為UI線程,不是則同Handler。post(action),如果是則action.run()直接運行
查看全部 -
getPostMessage(Runnable r)中將r對象賦值給message的callback屬性,最后在處理消息時如果callback不為null,則執行callback,不在同Handler將消息分發給handlerMessage方法了
查看全部 -
Handler post Runnable 方法的源碼跟入解讀
查看全部 -
通過HandlerThread 對象 使得Handler與子線程關聯,并向子線程中發送消息,在子線程的消息循環中處理消息;
HandlerThread中包含了線程同步的邏輯,保證Looper對象不為null
查看全部 -
與線程相關的Handler代碼示例:
Handler通過當前線程的mThreadLocal.get()方法得到Looper對象查看全部 -
從MessageQueue中取出的Message后給Message對象設置target,該target就是handler對象本身,handler分發消息并處理消息
查看全部 -
Handler 發送消息的過程實際上是利用主線程中的Looper對象的MessageQueue成員變量,將消息放到消息隊列中
查看全部 -
Handler 發送消息源碼跟入
查看全部 -
Handler的dispatchMessage(Message msg)源碼解析:
if(msg.callback !=null){
? handlerCalback(msg);
}else{
? if(mCallback !=null){
? ? if(mCallback.handleMessage(msg)){return}
? }
? handleMessage(msg);
}
查看全部 -
最終通過消息的target將消息發給Handler,進行處理。源代碼:
msg.target.dispatchMessage(msg); // target即為Handler對象
查看全部 -
Looper.loop()方法源碼解讀
通過myLooper()方法取出Looper對象,進而取出MessageQueue對象,最后從MessageQueue消息隊列中取出消息(queue.next())
查看全部 -
消息放到消息隊列中的源碼
queue.enqueueMessage(msg,uptimeMills);
查看全部 -
進而得到Looper對象當中的成員變量MessageQueue,進而循環放入、取出消息并傳給Handler進行消息循環處理
查看全部 -
Handler 關聯 Looper的源代碼
mLooper = Looper.myLooper()// myLooper通過mThreadLocal.get()方法返回線程關聯的Looper對象
查看全部 -
Lopper對象中包含成員變量MessageQueue,線程標記mThread
查看全部 -
Looper.prepareMainLooper() 通過ActivityThread的ThreadLocal成員變量關聯了Looper和當前線程(即主線程)
查看全部 -
main方法中
Looper.prepareMainLooper()
查看全部 -
回顧ActivityThread main方法 : Looper Message
查看全部 -
Handler / Looper / MessageQueue 總結
查看全部 -
為何只能通過Handler進行更新UI?
解決多線程并發問題;
查看全部 -
Handler / Looper / MessageQueue 三者的關系
查看全部
舉報