Handler我們經(jīng)常用砸烦,一般是用在子線程給主線程發(fā)消息,通知主線程做更新UI的操作杨拐,但是現(xiàn)在假如說(shuō)哗脖,讓你在主線程給子線程發(fā)消息呢瀑踢?
public class MainActivity extends Activity {
private MyLinearLayout mParent;
private Handler subHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
Button button = findViewById(R.id.my_button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
subHandler.sendEmptyMessage(0);
}
});
}
private void init() {
new Thread("子線程哈哈") {
@Override
public void run() {
//創(chuàng)建looper對(duì)象,并與當(dāng)前線程綁定
Looper.prepare();
subHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
Toast.makeText(MainActivity.this, "當(dāng)前線程:" + Thread.currentThread()
.getName() , Toast.LENGTH_SHORT).show();
return true;
}
});
//輪詢Looper里面的消息隊(duì)列
Looper.loop();
}
}.start();
}
上面就是使用Handler在主線程給子線程發(fā)消息的demo才避,點(diǎn)擊按鈕后橱夭,主線程發(fā)消息給子線程,子線程收到消息后桑逝,Toast的結(jié)果是:當(dāng)前線程:子線程哈哈.
但是如果我把Looper.prepare();
去掉棘劣,就會(huì)報(bào)錯(cuò):java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
對(duì)比在主線程創(chuàng)建handler,在子線程給主線程發(fā)消息的使用方式肢娘,唯一的區(qū)別就是加了2行代碼:
Looper.prepare();
........
Looper.loop();
那為什么呈础,在主線程中創(chuàng)建handler,我們直接new就可以橱健,但是在子線程不行呢?Hanlder的工作原理是什么沙廉?源碼是最好的老師拘荡,所以下面學(xué)習(xí)一下Handler的源碼
學(xué)習(xí)Handler的源碼之前,首先回顧一下一般情況下Handler的基本使用步驟:
1撬陵, 在主線程直接創(chuàng)建一個(gè)Handler對(duì)象珊皿,重寫(xiě)或?qū)崿F(xiàn)
handlerMessage()
,在handlerMessage()
里面寫(xiě)收到消息后的處理邏輯
2巨税, 在子線程中需要通知主線程的地方蟋定,調(diào)用handler.sendMessage()
只有2步,使用起來(lái)很簡(jiǎn)單. 我們就順著這個(gè)使用步驟去看Handler的源碼草添,看它到底怎么工作的驶兜,怎么就能夠讓2個(gè)不同的線程之間能夠通信
Handler的構(gòu)造方法:
public Handler() {
this(null, false);
}
public Handler(Callback callback) {
this(callback, false);
}
public Handler(Looper looper) {
this(looper, null, false);
}
public Handler(Looper looper, Callback callback) {
this(looper, callback, false);
}
public Handler(boolean async) {
this(null, async);
}
public Handler(Callback callback, boolean async) {
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());
}
}
//從當(dāng)前線程的ThreadLocalMap里面查找有沒(méi)有對(duì)應(yīng)的looper
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue; //將looper的Queue賦值handler的成員mQueue
mCallback = callback;
mAsynchronous = async;
}
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
Looper.myLooper()
Handler有7個(gè)重載的構(gòu)造方法,我們直接看倒數(shù)第二種構(gòu)造方式远寸,可以看到調(diào)用了mLooper = Looper.myLooper();
:
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
sThreadLocal
是Looper
類的一個(gè)靜態(tài)成員抄淑,它是一個(gè)ThreadLocal
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
所以通過(guò)上面的代碼可以看到,Looper.myLooper()
就是取出當(dāng)前線程的ThreadLocalMap里面存儲(chǔ)的key為Looper
的靜態(tài)成員sThreadLocal
所對(duì)應(yīng)的looper對(duì)象.(有關(guān)ThreadLoca知識(shí)驰后,請(qǐng)前往深入理解 Java 之 ThreadLocal 工作原理)
如果當(dāng)前線程(Handler在哪個(gè)線程創(chuàng)建就代表哪個(gè)線程)的ThreadLocalMap里面沒(méi)有Looper
對(duì)象肆资,就會(huì)報(bào)錯(cuò)提示:不能在沒(méi)有調(diào)用Looper.prepare()
的線程里創(chuàng)建Handler對(duì)象,如果有Looper
灶芝,就將Looper
的mQueue
賦值給Handler
的成員mQueue
Looper.prepare()
前面提到郑原,如果要?jiǎng)?chuàng)建Handler對(duì)象唉韭,必須要有Looper,如果沒(méi)有Looper犯犁,會(huì)報(bào)錯(cuò)提示要調(diào)用Looper.prepare()
才可以創(chuàng)建属愤,接下來(lái)就看一下Looper.prepare()
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
先從當(dāng)前線程的ThreadLocalMap
里面去取出key為Looper
類的靜態(tài)成員sThreadLocal
對(duì)應(yīng)的looper對(duì)象,如果已經(jīng)有l(wèi)ooper,就報(bào)錯(cuò):每一個(gè)線程只能有一個(gè)looper對(duì)象. 如果沒(méi)有l(wèi)ooper栖秕,就新建一個(gè)春塌,并存入當(dāng)前線程的ThreadLocalMap
,存入的key是Looper
類的sThreadLocal
. 看到這里簇捍,我們可能會(huì)想平時(shí)我們用的時(shí)候并沒(méi)有去調(diào)用Looper.prepare()
只壳,其實(shí)是系統(tǒng)已經(jīng)幫我們做了:
//ActivityThread#main()
public static void main(String[] args) {
........
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
在應(yīng)用程序的入口ActivityThread
的main()
方法里面(ActivityThread不是一個(gè)線程,只是一個(gè)普通類)暑塑,調(diào)用 了Looper.prepareMainLooper();
public static void prepareMainLooper() {
//新建一個(gè)looper對(duì)象,并存進(jìn)ThreadLocalMap
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
//給主線程對(duì)應(yīng)的looper賦值
sMainLooper = myLooper();
}
}
Looper也有一個(gè)獲取主線程對(duì)應(yīng)的looper的方法getMainLooper()
:
public static Looper getMainLooper() {
synchronized (Looper.class) {
return sMainLooper;
}
}
再看一下Looper
的構(gòu)造方法:
private Looper(boolean quitAllowed) {
//Looper對(duì)象創(chuàng)建的時(shí)候吼句,會(huì)創(chuàng)建一個(gè) MessageQueue
mQueue = new MessageQueue(quitAllowed);
//Looper對(duì)應(yīng)的線程
mThread = Thread.currentThread();
}
Handler初始化過(guò)程總結(jié)
從前面Handler的創(chuàng)建過(guò)程源碼可以得出:
1,創(chuàng)建Handler對(duì)象之前事格,必須要先創(chuàng)建Looper惕艳,Looper與線程對(duì)應(yīng),一個(gè)線程只能有一個(gè)Looper
2驹愚,創(chuàng)建Handler對(duì)象之前远搪,會(huì)先檢查Handler對(duì)象創(chuàng)建時(shí)所在的線程是否已經(jīng)有一個(gè)對(duì)應(yīng)的Looper,檢查是通過(guò)調(diào)用Looper.myLooper()
方法逢捺,內(nèi)部原理是通過(guò)每個(gè)線程內(nèi)部的ThreadLocalMap
查找key為Looper
的靜態(tài)成員ThreadLocal
對(duì)應(yīng)的Looper對(duì)象是否為null
3谁鳍,如果Handler對(duì)象創(chuàng)建時(shí)所在的線程沒(méi)有對(duì)應(yīng)的Looper,那么會(huì)拋異常劫瞳,在主線程創(chuàng)建除外倘潜。所以在主線程以外的線程創(chuàng)建Handler之前要先調(diào)用Looper.prepare()
創(chuàng)建一個(gè)Looper,該方法內(nèi)部同時(shí)會(huì)把Looper
的靜態(tài)成員ThreadLocal
作為key志于,把Looper對(duì)象做為value值涮因,存進(jìn)Handler對(duì)象創(chuàng)建時(shí)所在的線程的ThreadLocalMap
,Looper就與當(dāng)前線程對(duì)應(yīng)了
4伺绽,Looper對(duì)象創(chuàng)建的時(shí)候养泡,會(huì)創(chuàng)建一個(gè)MessageQueue
,該MessageQueue
會(huì)在構(gòu)造Handler對(duì)象的時(shí)候憔恳,賦值給Handler的成員mQueue
瓤荔,Looper對(duì)象本身也會(huì)賦值給Handler的成員mLooper
消息的發(fā)送
有了Handler對(duì)象后,就可以發(fā)送消息了钥组,看一下Handler發(fā)送消息的方法:
public final boolean sendMessage(Message msg){
return sendMessageDelayed(msg, 0);
}
public final boolean sendEmptyMessage(int what)
{
return sendEmptyMessageDelayed(what, 0);
}
public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageDelayed(msg, delayMillis);
}
public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageAtTime(msg, uptimeMillis);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
//第二個(gè)參數(shù)傳遞的是從系統(tǒng)開(kāi)機(jī)到當(dāng)前時(shí)間的毫秒數(shù)+延遲時(shí)間
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
//第二個(gè)參數(shù)uptimeMillis表示消息發(fā)送的時(shí)間
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
//Handler的成員mQueue就是構(gòu)造Handler對(duì)象時(shí)输硝,Looper里面的MessageQueue
MessageQueue queue = mQueue;
if (queue == null) {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
return false;
}
return enqueueMessage(queue, msg, uptimeMillis);
}
public final boolean sendMessageAtFrontOfQueue(Message msg) {
MessageQueue queue = mQueue;
if (queue == null) {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
return false;
}
//發(fā)送消息到消息隊(duì)列的頭部,因?yàn)榈谌齻€(gè)參數(shù)傳的是0
return enqueueMessage(queue, msg, 0);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
//把Handler賦值給Message的target程梦,后面從消息隊(duì)列取出消息后就是交給這個(gè)target(Handler)處理
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
上面那么多發(fā)送消息的方法点把,除了sendMessageAtFrontOfQueue()
以外橘荠,其余都是調(diào)用sendMessageAtTime()
,這兩個(gè)方法其實(shí)也是一樣的郎逃,sendMessageAtTime()
的第二個(gè)參數(shù)傳0這兩個(gè)方法就是一樣了哥童。但是這兩個(gè)方法最終都調(diào)用了enqueueMessage()
,而enqueueMessage()
又調(diào)用了MessageQueue
的enqueueMessage()
褒翰,也就是把消息插入到消息隊(duì)列
消息入隊(duì)
boolean enqueueMessage(Message msg, long when) {
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) { //如果消息隊(duì)列退出了,還入隊(duì)就報(bào)錯(cuò)
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(); //消息入隊(duì)后贮懈,標(biāo)記為在被使用
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
//p為null(代表MessageQueue沒(méi)有消息) 或者消息的發(fā)送時(shí)間是隊(duì)列中最早的
msg.next = p;
mMessages = msg;
needWake = mBlocked; //當(dāng)阻塞時(shí)需要喚醒
} 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;
//將消息按時(shí)間順序插入到MessageQueue
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
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;
}
Looper.loop();
消息插入到消息隊(duì)列了,肯定要取出來(lái)才能用优训,從消息隊(duì)列取消息的方法就是開(kāi)頭demo中的Looper.loop();
public static void loop() {
//取出當(dāng)前線程對(duì)應(yīng)的looper
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
//取出looper里面的消息隊(duì)列
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();
//死循環(huán)
for (;;) {
Message msg = queue.next(); // 從消息隊(duì)列取出消息朵你,會(huì)阻塞
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
.......
try {
//分發(fā)消息,把消息交給msg.target也就是Handler處理
msg.target.dispatchMessage(msg);
end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
........
msg.recycleUnchecked(); //將不再使用的消息放入消息池
}
}
消息出隊(duì)
取消息的時(shí)候揣非,調(diào)用了消息隊(duì)列的消息出隊(duì)方法next()
//MessageQueue #next()
Message next() {
final long ptr = mPtr;
if (ptr == 0) { //當(dāng)消息循環(huán)已經(jīng)退出抡医,則直接返回
return null;
}
int pendingIdleHandlerCount = -1; // 循環(huán)迭代的首次為-1
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
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) {
//如果消息沒(méi)有 target,那它就是一個(gè)屏障早敬,需要一直往后遍歷找到第一個(gè)異步的消息
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) { //如果這個(gè)消息還沒(méi)到處理時(shí)間忌傻,就設(shè)置個(gè)時(shí)間過(guò)段時(shí)間再處理
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// 正常消息的處理
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next; //取出當(dāng)前消息,鏈表頭結(jié)點(diǎn)后移一位
} else {
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
return msg;
}
} else {
//沒(méi)有消息
nextPollTimeoutMillis = -1;
}
// Process the quit message now that all pending messages have been handled.
if (mQuitting) {
dispose();
return null;
}
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);
}
// 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);
}
}
}
pendingIdleHandlerCount = 0;
nextPollTimeoutMillis = 0;
}
}
Handler.dispatchMessage()
Looper.loop()
里面從消息取出消息后搞监,調(diào)用了msg.target.dispatchMessage(msg);
public void dispatchMessage(Message msg) {
if (msg.callback != null) { //
handleCallback(msg);
} else {
if (mCallback != null) { //構(gòu)造Handler的時(shí)候傳入的Callback
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg); //構(gòu)造Handler時(shí)候水孩,Callback如果傳null,就走這里,它是空實(shí)現(xiàn)
}
}
一般情況下琐驴,我們使用Handler都是使用 Handler handler=new Handler()
這種構(gòu)造方式荷愕,通過(guò)前面Handler的構(gòu)造方法源碼可以知道,這種構(gòu)造方式的mCallback
傳的是null(不是Message的callback)棍矛,所以當(dāng)handler取出消息要處理的時(shí)候,會(huì)回調(diào)handleMessage(msg);
而它是空實(shí)現(xiàn)抛杨,所以我們需要覆寫(xiě)handleMessage()
那么什么時(shí)候會(huì)調(diào)用if條件語(yǔ)句里面的handleCallback(msg)
呢够委,其實(shí)Handler不僅只有sendMessageXXX
發(fā)送消息方法,還有postXXX
發(fā)送消息的方法
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
public final boolean postAtTime(Runnable r, long uptimeMillis)
{
return sendMessageAtTime(getPostMessage(r), uptimeMillis);
}
public final boolean postAtTime(Runnable r, Object token, long uptimeMillis)
{
return sendMessageAtTime(getPostMessage(r, token), uptimeMillis);
}
public final boolean postDelayed(Runnable r, long delayMillis)
{
return sendMessageDelayed(getPostMessage(r), delayMillis);
}
public final boolean postAtFrontOfQueue(Runnable r)
{
return sendMessageAtFrontOfQueue(getPostMessage(r));
}
有5個(gè)postXXX
發(fā)送消息的方法怖现,但還是調(diào)用了sendXXX
方法茁帽,只是傳遞參數(shù)的過(guò)程中調(diào)用了一個(gè)getPostMessage()
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
看到這里就明白了,只有調(diào)用postXXX
發(fā)送消息的方法屈嗤,才會(huì)走Handler.dispatchMessage()
的if語(yǔ)句里面的回調(diào)潘拨,其實(shí)我們常用更新UI的方式:Activity.runOnUiThread(Runnable)
, View.post(Runnable)
;和View.postDelayed(Runnable action, long delayMillis)
都是調(diào)用Handler的post方法發(fā)送消息
//Activity#runOnUiThread
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action); //這個(gè)Handler是Activity的成員變量
} else {
action.run();
}
}
//View#post
public boolean post(Runnable action) {
final AttachInfo attachInfo = mAttachInfo;
if (attachInfo != null) {
return attachInfo.mHandler.post(action);
}
// Postpone the runnable until we know on which thread it needs to run.
// Assume that the runnable will be successfully placed after attach.
getRunQueue().post(action);
return true;
}
關(guān)于Message的其他知識(shí)
1,
Message
的成員what
表示的是消息的類型(用于標(biāo)識(shí)干什么用的)
2饶号,獲取一個(gè)Message
對(duì)象最好的方式不是直接new铁追,而是使用Message.obtain()
,或者Handler.obtainMessage()
這種方式會(huì)復(fù)用消息池中的消息茫船,而不是新建
最后再總結(jié)一下Handler機(jī)制:
1琅束,每一個(gè)Handler創(chuàng)建的時(shí)候必須要有一個(gè)Looper(要么傳入扭屁,要么通過(guò)當(dāng)前線程獲取),每一個(gè)Looper對(duì)應(yīng)一個(gè)線程和MessageQueue涩禀,一個(gè)線程可以創(chuàng)建多個(gè)Handler料滥,但只能創(chuàng)建一個(gè)Looper
2,如果Handler創(chuàng)建時(shí)所在的線程和Looper創(chuàng)建時(shí)所在的線程是同一個(gè)線程艾船,Handler對(duì)象創(chuàng)建的時(shí)候會(huì)通過(guò)當(dāng)前線程的ThreadLocal的內(nèi)部類ThreadLocalMap檢查當(dāng)前線程是否已經(jīng)有一個(gè)Looper葵腹,如果是在主線程創(chuàng)建的Handler,Looper的創(chuàng)建和輪詢消息隊(duì)列的操作屿岂,主線程已經(jīng)在ActivityThread已經(jīng)幫我們做了践宴,如果不是在主線程創(chuàng)建的Handler,需要我們自己手動(dòng)調(diào)用Looper.prepare()來(lái)創(chuàng)建Looper和調(diào)用Looper.loop()輪詢消息隊(duì)列雁社,如果我們不手動(dòng)調(diào)用浴井,會(huì)報(bào)錯(cuò)!特別注意:Handler的創(chuàng)建線程可以和Looper的創(chuàng)建線程不是同一個(gè)線程
3霉撵,Handler對(duì)象創(chuàng)建的時(shí)候磺浙,會(huì)把Looper持有的MessageQueue賦值給Handler的MessageQueue,同時(shí)也會(huì)把Looper賦值給Handler的Looper徒坡,Handler發(fā)消息其實(shí)是把消息發(fā)送到Looper的MessageQueue撕氧,也就是說(shuō)Handler持有的Looper在哪個(gè)線程創(chuàng)建的(Looper.prepare()
和Looper.loop()
一般都會(huì)在一個(gè)線程),消息也就發(fā)給哪個(gè)線程
4喇完,發(fā)送消息的過(guò)程中伦泥,Handler會(huì)把自身設(shè)置為當(dāng)前消息的Target(Handler.enqueueMessage()
里面設(shè)置),這樣即使在一個(gè)線程創(chuàng)建了多個(gè)Handler锦溪,接收的Handler就永遠(yuǎn)是那個(gè)發(fā)送的Handler不脯,而不會(huì)是別的Handler,別且這多個(gè)Handler共用一個(gè)Looper和MessageQueue