Handler我們經(jīng)常用,一般是用在子線程給主線程發(fā)消息,通知主線程做更新UI的操作,但是現(xiàn)在假如說,讓你在主線程給子線程發(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對象,并與當(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();去掉,就會報(bào)錯(cuò):java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
對比在主線程創(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對象,重寫或?qū)崿F(xiàn)
handlerMessage(),在handlerMessage()里面寫收到消息后的處理邏輯
2, 在子線程中需要通知主線程的地方,調(diào)用handler.sendMessage()
只有2步,使用起來很簡單. 我們就順著這個(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里面查找有沒有對應(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>();
所以通過上面的代碼可以看到,Looper.myLooper()就是取出當(dāng)前線程的ThreadLocalMap里面存儲的key為Looper的靜態(tài)成員sThreadLocal所對應(yīng)的looper對象.(有關(guān)ThreadLoca知識,請前往深入理解 Java 之 ThreadLocal 工作原理)
如果當(dāng)前線程(Handler在哪個(gè)線程創(chuàng)建就代表哪個(gè)線程)的ThreadLocalMap里面沒有Looper對象,就會報(bào)錯(cuò)提示:不能在沒有調(diào)用Looper.prepare()的線程里創(chuàng)建Handler對象,如果有Looper,就將Looper的mQueue賦值給Handler的成員mQueue
Looper.prepare()
前面提到,如果要?jiǎng)?chuàng)建Handler對象,必須要有Looper,如果沒有Looper,會報(bào)錯(cuò)提示要調(diào)用Looper.prepare()才可以創(chuàng)建,接下來就看一下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對應(yīng)的looper對象,如果已經(jīng)有l(wèi)ooper,就報(bào)錯(cuò):每一個(gè)線程只能有一個(gè)looper對象. 如果沒有l(wèi)ooper,就新建一個(gè),并存入當(dāng)前線程的ThreadLocalMap,存入的key是Looper類的sThreadLocal. 看到這里,我們可能會想平時(shí)我們用的時(shí)候并沒有去調(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對象,并存進(jìn)ThreadLocalMap
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
//給主線程對應(yīng)的looper賦值
sMainLooper = myLooper();
}
}
Looper也有一個(gè)獲取主線程對應(yīng)的looper的方法getMainLooper():
public static Looper getMainLooper() {
synchronized (Looper.class) {
return sMainLooper;
}
}
再看一下Looper的構(gòu)造方法:
private Looper(boolean quitAllowed) {
//Looper對象創(chuàng)建的時(shí)候,會創(chuàng)建一個(gè) MessageQueue
mQueue = new MessageQueue(quitAllowed);
//Looper對應(yīng)的線程
mThread = Thread.currentThread();
}
Handler初始化過程總結(jié)
從前面Handler的創(chuàng)建過程源碼可以得出:
1,創(chuàng)建Handler對象之前,必須要先創(chuàng)建Looper,Looper與線程對應(yīng),一個(gè)線程只能有一個(gè)Looper
2,創(chuàng)建Handler對象之前,會先檢查Handler對象創(chuàng)建時(shí)所在的線程是否已經(jīng)有一個(gè)對應(yīng)的Looper,檢查是通過調(diào)用Looper.myLooper()方法,內(nèi)部原理是通過每個(gè)線程內(nèi)部的ThreadLocalMap查找key為Looper的靜態(tài)成員ThreadLocal對應(yīng)的Looper對象是否為null
3,如果Handler對象創(chuàng)建時(shí)所在的線程沒有對應(yīng)的Looper,那么會拋異常,在主線程創(chuàng)建除外。所以在主線程以外的線程創(chuàng)建Handler之前要先調(diào)用Looper.prepare()創(chuàng)建一個(gè)Looper,該方法內(nèi)部同時(shí)會把Looper的靜態(tài)成員ThreadLocal作為key,把Looper對象做為value值,存進(jìn)Handler對象創(chuàng)建時(shí)所在的線程的ThreadLocalMap,Looper就與當(dāng)前線程對應(yīng)了
4,Looper對象創(chuàng)建的時(shí)候,會創(chuàng)建一個(gè)MessageQueue,該MessageQueue會在構(gòu)造Handler對象的時(shí)候,賦值給Handler的成員mQueue,Looper對象本身也會賦值給Handler的成員mLooper
消息的發(fā)送
有了Handler對象后,就可以發(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)開機(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對象時(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沒有消息) 或者消息的發(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ì)列了,肯定要取出來才能用,從消息隊(duì)列取消息的方法就是開頭demo中的Looper.loop();
public static void loop() {
//取出當(dāng)前線程對應(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ì)列取出消息,會阻塞
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) {
//如果消息沒有 target,那它就是一個(gè)屏障,需要一直往后遍歷找到第一個(gè)異步的消息
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) { //如果這個(gè)消息還沒到處理時(shí)間,就設(shè)置個(gè)時(shí)間過段時(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 {
//沒有消息
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)造方式,通過前面Handler的構(gòu)造方法源碼可以知道,這種構(gòu)造方式的mCallback傳的是null(不是Message的callback),所以當(dāng)handler取出消息要處理的時(shí)候,會回調(diào)handleMessage(msg);而它是空實(shí)現(xiàn),所以我們需要覆寫handleMessage()
那么什么時(shí)候會調(diào)用if條件語句里面的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ù)的過程中調(diào)用了一個(gè)getPostMessage()
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
看到這里就明白了,只有調(diào)用postXXX發(fā)送消息的方法,才會走Handler.dispatchMessage()的if語句里面的回調(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的其他知識
1,
Message的成員what表示的是消息的類型(用于標(biāo)識干什么用的)
2,獲取一個(gè)Message對象最好的方式不是直接new,而是使用Message.obtain(),或者Handler.obtainMessage()這種方式會復(fù)用消息池中的消息,而不是新建
最后再總結(jié)一下Handler機(jī)制:
1,每一個(gè)Handler創(chuàng)建的時(shí)候必須要有一個(gè)Looper(要么傳入,要么通過當(dāng)前線程獲取),每一個(gè)Looper對應(yīng)一個(gè)線程和MessageQueue,一個(gè)線程可以創(chuàng)建多個(gè)Handler,但只能創(chuàng)建一個(gè)Looper
2,如果Handler創(chuàng)建時(shí)所在的線程和Looper創(chuàng)建時(shí)所在的線程是同一個(gè)線程,Handler對象創(chuàng)建的時(shí)候會通過當(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()來創(chuàng)建Looper和調(diào)用Looper.loop()輪詢消息隊(duì)列,如果我們不手動(dòng)調(diào)用,會報(bào)錯(cuò)!特別注意:Handler的創(chuàng)建線程可以和Looper的創(chuàng)建線程不是同一個(gè)線程
3,Handler對象創(chuàng)建的時(shí)候,會把Looper持有的MessageQueue賦值給Handler的MessageQueue,同時(shí)也會把Looper賦值給Handler的Looper,Handler發(fā)消息其實(shí)是把消息發(fā)送到Looper的MessageQueue,也就是說Handler持有的Looper在哪個(gè)線程創(chuàng)建的(Looper.prepare()和Looper.loop()一般都會在一個(gè)線程),消息也就發(fā)給哪個(gè)線程
4,發(fā)送消息的過程中,Handler會把自身設(shè)置為當(dāng)前消息的Target(Handler.enqueueMessage()里面設(shè)置),這樣即使在一個(gè)線程創(chuàng)建了多個(gè)Handler,接收的Handler就永遠(yuǎn)是那個(gè)發(fā)送的Handler,而不會是別的Handler,別且這多個(gè)Handler共用一個(gè)Looper和MessageQueue