handler原始碼學習(2) Message

2021-10-13 09:53:33 字數 1546 閱讀 5094

這是handler原始碼學習第二篇,後續還有

handler原始碼學習(1) — handler

handler原始碼學習(2) — message

handler原始碼學習(3) — looper

handler原始碼學習(4) — messagequeue

message相對來說比較簡單,大部門**都是對一些屬性值的賦值和獲取以及parcelable的實現。這裡我們主要看一下幾個方法

public

message()

/ 1public

static message obtain()

}return

newmessage()

;}public

static message obtain

(message orig)

public

static message obtain

(handler h)

public

static message obtain

(handler h, runnable callback)

public

static message obtain

(handler h,

int what)

public

static message obtain

(handler h,

int what, object obj)

public

static message obtain

(handler h,

int what,

int arg1,

int arg2)

public

static message obtain

(handler h,

int what,

int arg1,

int arg2, object obj)

重點看下注釋1,其他都是很常規的一些方法。

說白了就是同步取spool(注意是靜態的)的第乙個,並且返回。不過這裡有個點需要關注,就是什麼時候對spool賦值,什麼時候新增next。我們找一下spool的賦值,很容易找到

void

recycleunchecked()

}}

其實就是將當前的message的所有變數置為初始狀態,同時(注釋1)將其新增到spool(是靜態的)的煉表頭。注釋1舉個例子:

val 當前msg = this;

spool = 1msg

當前msg.next = 1msg

spool =當前msg(當前msg.next = 1msg)

所以此時的spool就是 當前msg,1msg

所以到這裡我們基本上就明白了obtain和直接new message()的區別。

message就如它的翻譯訊息。他就是乙個標準的訊息,裡面包含了我們跨執行緒要傳遞的東西。

本篇我們解決了問題:

留下疑問:

Handler原始碼解析2

handler原始碼解析1 handler原始碼解析2 享元設計模式 記憶體復用,使用同一塊記憶體空間,bitmap,recycleview都有使用這種思想 在loop從訊息佇列中取出訊息並分發完後,並不會把訊息物件銷毀,而是通過msg.recycleunchecked 方法清空訊息放入訊息池進行 ...

Handler原始碼解析2

handler原始碼解析1 handler原始碼解析2 享元設計模式 記憶體復用,使用同一塊記憶體空間,bitmap,recycleview都有使用這種思想 在loop從訊息佇列中取出訊息並分發完後,並不會把訊息物件銷毀,而是通過msg.recycleunchecked 方法清空訊息放入訊息池進行 ...

Handler原始碼解析

意思就是說 在沒有呼叫looper.prepare 之前不能在子執行緒建立handler。為什麼在主線程中我們就已經可以直接建立handler?因為在activity的啟動 中,已經在當前ui執行緒 主線程 呼叫了looper.preparemainlooper 和looper.loop 方法。我們...