1.Handler
- 只要是開(kāi)發(fā)Android的同學(xué),Handler這個(gè)經(jīng)常都會(huì)看到,也會(huì)使用到,本文章就做個(gè)筆記。
- Android規(guī)定了只能在主線程更新UI,那子線程想更新UI,在操作完成后,就可用通過(guò)Handler發(fā)消息,然后在主線程更新UI了。其實(shí)可以理解為生產(chǎn)者-消費(fèi)者模式,發(fā)送消息,取出消息并處理。
- Android系統(tǒng)源碼中,Android的消息機(jī)制中,大量使用Handler,所以了解Handler非常的有必要。
-
下圖是一個(gè)消息發(fā)送的簡(jiǎn)易流程,一各個(gè)步驟分析。
Handler
2.Handler簡(jiǎn)單使用
2.1 發(fā)送消息
- 最基本的使用就是各種sendMessage,帶不帶參數(shù),是否延遲等。
- 發(fā)送消息方法非常多,根據(jù)自己需求選擇,所有發(fā)送消息最后都是
- enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,long uptimeMillis)。
發(fā)送消息
2.2 使用
- 這樣直接使用會(huì)有內(nèi)存泄漏風(fēng)險(xiǎn),后面說(shuō)。
- Handler創(chuàng)建有兩種,一個(gè)是在構(gòu)造方法傳CallBack,一個(gè)是重寫類的 handleMessage() 方法。
private static final int MESSAGA_TEST_1 = 1;
/**
* 主線程有初始化好Looper,所以在主線程處理消息
*/
private Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(@NonNull Message msg) {
switch (msg.what) {
case MESSAGA_TEST_1:
if (tvTest != null) {
//傳遞消息obj
tvTest.setText((String) msg.obj);
}
break;
}
return false;
}
});
private Handler mHandler2 = new Handler() {
@Override
public void handleMessage(@NonNull Message msg) {
switch (msg.what) {
case MESSAGA_TEST_1:
if (tvTest != null) {
//傳遞消息obj
tvTest.setText((String) msg.obj);
}
break;
}
}
};
private void onClick() {
//當(dāng)點(diǎn)擊事件執(zhí)行,就會(huì)在子線程發(fā)送消息更新textview
new Thread(new Runnable() {
@Override
public void run() {
clickEndMessage();
}
}).start();
}
/**
* 可以在子線程發(fā)送
*/
private void clickEndMessage() {
//obtain享元模式
Message message = Message.obtain(mHandler);
//what相當(dāng)于標(biāo)記
message.what = MESSAGA_TEST_1;
//obj傳數(shù)據(jù)
message.obj = new String("baozi");
//普通發(fā)送message
mHandler.sendMessage(message);
.
.
.
//發(fā)送標(biāo)記,不帶其他內(nèi)容,內(nèi)部會(huì)封裝成只有標(biāo)記的Message對(duì)象
mHandler.sendEmptyMessage();
//尾部帶有Delayed,發(fā)送延遲消息,單位毫秒
mHandler.sendMessageDelayed(message, 1000);
//尾部帶有AtTime,發(fā)送消息的時(shí)間跟Delayed差別就是Delayed是執(zhí)行的當(dāng)前時(shí)間+傳進(jìn)去的時(shí)間,AtTime就傳進(jìn)去的絕對(duì)時(shí)間
mHandler.sendMessageAtTime();
//在隊(duì)列頭插入消息
mHandler.sendMessageAtFrontOfQueue(message);
}
@Override
protected void onDestroy() {
if(mHandler!=null){
//關(guān)閉activity時(shí),移除消息
mHandler.removeMessages(MESSAGA_TEST_1);
mHandler = null;
}
super.onDestroy();
}
2.3 view.post()
- 比如view,post()、postDelayed() 方法,可以延遲五秒后更新UI,實(shí)際就是使用Handler。
tvTest.postDelayed(new Runnable() {
@Override
public void run() {
tvTest.setText("5s");
}
},5*1000);
/**
* View 源碼
*/
public boolean postDelayed(Runnable action, long delayMillis) {
final AttachInfo attachInfo = mAttachInfo;
if (attachInfo != null) {
return attachInfo.mHandler.postDelayed(action, delayMillis);
}
// Postpone the runnable until we know on which thread it needs to run.
// Assume that the runnable will be successfully placed after attach.
getRunQueue().postDelayed(action, delayMillis);
return true;
}
2.4 runOnUiThread
- 經(jīng)常用的 runOnUiThread() 方法也是用Handler。
runOnUiThread(new Runnable() {
@Override
public void run() {
//更新UI
}
});
/**
* Activity 源碼
*/
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}
3.子線程中使用
3.1 子線程直接創(chuàng)建Handler錯(cuò)誤
- 子線程不能直接創(chuàng)建Handler,會(huì)報(bào)異常,因?yàn)長(zhǎng)ooper還沒(méi)創(chuàng)建,而主線程默認(rèn)就初始化好Looper。
- 應(yīng)該先Looper.
private Handler handler2;
/**
* 子線程
*/
private void thread() {
new Thread(new Runnable() {
@Override
public void run() {
handler2 = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(@NonNull Message msg) {
return false;
}
});
}
}).start();
}
-
提示的錯(cuò)誤。
子線程創(chuàng)建Handler
3.2 主線程默認(rèn)初始化Looper
- ActivityThread 類就能主線程找到Looper初始化,Looper.prepareMainLooper();。
public static void main(String[] args) {
.
.
Looper.prepareMainLooper();
.
.
ActivityThread thread = new ActivityThread();
.
.
}
3.3 Handler構(gòu)造方法查看
- 構(gòu)造方法中可以看到 mLooper = Looper.myLooper(); 獲取的 mLooper 為null,就報(bào)上面的那個(gè)異常了。
public Handler(@Nullable Callback callback, boolean async) {
.
.
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
.
.
}
3.4 子線程正確的創(chuàng)建
- 先執(zhí)行,Looper.prepare(); 初始化Looper,然后調(diào)用loop()方法,再創(chuàng)建Handler。
- 每個(gè)線程Looper.prepare();只能調(diào)用一次,否則會(huì)報(bào)錯(cuò)。
private Handler handler2;
/**
* 子線程
*/
private void thread() {
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
Looper looper = Looper.myLooper();
looper.loop();
handler2 = new Handler(looper, new Handler.Callback() {
@Override
public boolean handleMessage(@NonNull Message msg) {
return false;
}
});
}
}).start();
}
4.Message
- Message就是一個(gè)存放消息的類,是一個(gè)鏈表結(jié)構(gòu)。
4.1 基本參數(shù)
public final class Message implements Parcelable {
//用于handler標(biāo)記處理的
public int what;
//可以傳遞的int參數(shù)1
public int arg1;
//可以傳遞的int參數(shù)2
public int arg2;
//可以傳遞的obj參數(shù)
public Object obj;
//執(zhí)行時(shí)間
public long when;
//傳遞的bundle
Bundle data;
//Message綁定的Handler
Handler target;
//Handler.post()時(shí)傳的callback
Runnable callback;
//鏈表結(jié)構(gòu)
Message next;
4.2 享元模式obtain()
- obtain() 可以重用Message,減少開(kāi)銷提高性能。
- 菜鳥(niǎo)教程-享元模式
/**
* Return a new Message instance from the global pool. Allows us to
* avoid allocating new objects in many cases.
*/
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
4.3 回收recycle()
- 如果發(fā)送的延遲消息,或者消息在執(zhí)行,就會(huì)報(bào)錯(cuò),一般我們不用調(diào)用recycle方法。
/**
* Return a Message instance to the global pool.
* <p>
* You MUST NOT touch the Message after calling this function because it has
* effectively been freed. It is an error to recycle a message that is currently
* enqueued or that is in the process of being delivered to a Handler.
* </p>
*/
public void recycle() {
if (isInUse()) {
if (gCheckRecycle) {
throw new IllegalStateException("This message cannot be recycled because it "
+ "is still in use.");
}
return;
}
recycleUnchecked();
}
- Message用完并不是內(nèi)存回收,只是把里面的內(nèi)容清空,等下次復(fù)用。
- 這個(gè)鏈表也不是無(wú)限的,最多就50個(gè)節(jié)點(diǎn) 。
private static final int MAX_POOL_SIZE = 50;
@UnsupportedAppUsage
void recycleUnchecked() {
// Mark the message as in use while it remains in the recycled object pool.
// Clear out all other details.
flags = FLAG_IN_USE;
what = 0;
arg1 = 0;
arg2 = 0;
obj = null;
replyTo = null;
sendingUid = UID_NONE;
workSourceUid = UID_NONE;
when = 0;
target = null;
callback = null;
data = null;
synchronized (sPoolSync) {
//最多50個(gè)
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
5.MessageQueue
- 這是一個(gè)阻塞隊(duì)列。
- 隊(duì)列是在不停的for循環(huán)的,是一個(gè)死循環(huán),那不就一直占用著cpu?所以就有了native的方法,處理休眠喚醒。
5.1 MessageQueue每個(gè)線程只有一個(gè)
- 消息隊(duì)列每個(gè)線程只有一個(gè),跟Looper綁定在一起,在分析Looper時(shí)會(huì)一起分析。
5.2 消息入隊(duì)
- 前面我們知道Handler所有消息入隊(duì)最后都是調(diào)用 enqueueMessage(Message msg, long when) 。
- 判斷插入消息的位置,還判斷是否喚醒操作。
boolean enqueueMessage(Message msg, long when) {
//handler為空就報(bào)異常
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
//加鎖
synchronized (this) {
//消息正在使用會(huì)報(bào)錯(cuò)
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
//判斷線程是否存活
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;
}
//標(biāo)記正在使用
msg.markInUse();
msg.when = when;
//鏈表頭
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
//如果隊(duì)列為空,或者消息延遲時(shí)間為0,或者延遲時(shí)間小于mMessage的,就插入在頭部
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
//喚醒隊(duì)列
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.
//插入隊(duì)列中間。通常,除非隊(duì)列的開(kāi)頭有障礙并且消息是隊(duì)列中最早的異步消息,否則我們不必喚醒事件隊(duì)列。
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
//在中間插入,根據(jù)時(shí)間位置插入
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;
}
5.3 消息出隊(duì)
- 消息出隊(duì)其實(shí)應(yīng)該放在 Looper.loop() 里面分析更合適,這里先寫,后面結(jié)合 loop() 一起看會(huì)更好。
- 前面 return null; 看注釋的意思是,如果looper已經(jīng)退出和釋放,就返回null。
- 這里無(wú)限循環(huán),就是一定要取到消息,有消息,阻塞時(shí)間為消息的執(zhí)行時(shí)間減去當(dāng)前時(shí)間,如果沒(méi)消息就阻塞, nativePollOnce(ptr, nextPollTimeoutMillis)。
- 這 next() 方法只有一個(gè)地方返回msg,關(guān)注這里就行了。
@UnsupportedAppUsage
Message next() {
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after quit
// which is not supported.
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();
}
//沒(méi)消息取就阻塞
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) {
// Stalled by a barrier. Find the next asynchronous message in the queue.
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
// Next message is not ready. Set a timeout to wake up when it is ready.
//阻塞時(shí)間為消息的執(zhí)行時(shí)間減去當(dāng)前時(shí)間
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();
//只有這里返回msg
return msg;
}
} else {
//沒(méi)有更多消息,設(shè)置為-1,阻塞
// No more messages.
nextPollTimeoutMillis = -1;
}
.
.
}
}
5.4 退出
- 主線程是不能退出。
- 傳入的 safe 處理,分別是移除消息未執(zhí)行的消息,和移除全部消息。
void quit(boolean safe) {
//主線程是不能退出的
if (!mQuitAllowed) {
throw new IllegalStateException("Main thread not allowed to quit.");
}
synchronized (this) {
if (mQuitting) {
return;
}
mQuitting = true;
//移除消息
if (safe) {
removeAllFutureMessagesLocked();
} else {
removeAllMessagesLocked();
}
// We can assume mPtr != 0 because mQuitting was previously false.
nativeWake(mPtr);
}
}
/**
* 移除全部消息
*/
private void removeAllMessagesLocked() {
Message p = mMessages;
while (p != null) {
Message n = p.next;
p.recycleUnchecked();
p = n;
}
mMessages = null;
}
/**
* 移除未執(zhí)行的消息,正在運(yùn)行的等待完成再回收
*/
private void removeAllFutureMessagesLocked() {
final long now = SystemClock.uptimeMillis();
Message p = mMessages;
if (p != null) {
if (p.when > now) {
//如果執(zhí)行時(shí)間還未到,即未執(zhí)行的消息,移除回收
removeAllMessagesLocked();
} else {
//等待在執(zhí)行的消息執(zhí)行完再回收移除
Message n;
for (;;) {
n = p.next;
if (n == null) {
return;
}
if (n.when > now) {
break;
}
p = n;
}
p.next = null;
do {
p = n;
n = p.next;
p.recycleUnchecked();
} while (n != null);
}
}
}
6.Looper
- Handler要負(fù)責(zé)發(fā)送消息,MessageQueue消息隊(duì)列存放消息,Looper就是負(fù)責(zé)消息循環(huán)。
- 商場(chǎng)的扶手電梯大家應(yīng)該都知道吧,可以把扶手電梯的電機(jī)看成Looper,一梯一梯看成消息隊(duì)列MessageQueue,坐電梯的人看成Message,就這樣不停的循環(huán),把消息送去處理。
6.1 ThreadLocal
- Android 開(kāi)發(fā)也要掌握的Java知識(shí) -ThreadLocal 可以看下ThreadLocal原理。
- Looper就是用到了ThreadLocal,Looper內(nèi)部直接就有一個(gè),還定義成static,final了,也就意味著Android里面獲取的ThreadLocal<Looper>只有這一個(gè)。
@UnsupportedAppUsage
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
6.2 初始化prepare(),為何只能調(diào)用一次
- 在prepare()方法可以看到,如果初始化過(guò),就調(diào)用就會(huì)報(bào)錯(cuò)了,所以每個(gè)線程最多只有一個(gè)Looper,但Handler可以有很多個(gè)。
/** Initialize the current thread as a looper.
* This gives you a chance to create handlers that then reference
* this looper, before actually starting the loop. Be sure to call
* {@link #loop()} after calling this method, and end it by calling
* {@link #quit()}.
*/
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
//每個(gè)線程只能有一個(gè)looper
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
//初始化后設(shè)置給sThreadLocal
sThreadLocal.set(new Looper(quitAllowed));
}
6.3 綁定當(dāng)前線程,創(chuàng)建消息對(duì)列
- 創(chuàng)建消息對(duì)列,Looper綁定到當(dāng)前Thread。
- quitAllowed消息隊(duì)列是否可銷毀,主線程的是不可銷毀的,子線程默認(rèn)是可銷毀。
private Looper(boolean quitAllowed) {
//創(chuàng)建消息隊(duì)列
mQueue = new MessageQueue(quitAllowed);
//綁定當(dāng)前線程
mThread = Thread.currentThread();
}
6.4 拿到當(dāng)前線程的looper
/**
* Return the Looper object associated with the current thread. Returns
* null if the calling thread is not associated with a Looper.
*/
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
6.5 loop()
- 首先拿到當(dāng)前線程的looper,如果沒(méi)有prepare()那就是空,報(bào)異常。
- 然后就是不停的循環(huán),取出消息,再處理消息。
- Android中為什么主線程不會(huì)因?yàn)長(zhǎng)ooper.loop()里的死循環(huán)卡死?
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
public static void loop() {
//拿到當(dāng)前線程的looper,如果沒(méi)有prepare()那就是空,報(bào)異常
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
if (me.mInLoop) {
Slog.w(TAG, "Loop again would have the queued messages be executed"
+ " before this one completed.");
}
.
.
.
for (;;) {
//不停的取消息
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
.
.
try {
//處理消息,msg.target就是綁定的handler
msg.target.dispatchMessage(msg);
if (observer != null) {
observer.messageDispatched(token, msg);
}
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} catch (Exception exception) {
if (observer != null) {
observer.dispatchingThrewException(token, msg, exception);
}
throw exception;
} finally {
ThreadLocalWorkSource.restore(origWorkSource);
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
.
.
//回收消息
msg.recycleUnchecked();
}
}
6.6 退出
- 退出 Looper 其實(shí)就是調(diào)用 MessageQueue 的退出,傳的 safe 不同而已,那這兩段注釋說(shuō)啥。
- 傳 false ,就是說(shuō)后面發(fā)送消息都不會(huì)再處理了,發(fā)送消息全部都失敗,而且該方法不安全,建議使用 quitSafely()。
- 傳 true,跟上面效果差不多,就是MessageQueue的邏輯,移除未執(zhí)行的消息,正在運(yùn)行的等待完成。
/**
* Quits the looper.
* <p>
* Causes the {@link #loop} method to terminate without processing any
* more messages in the message queue.
* </p><p>
* Any attempt to post messages to the queue after the looper is asked to quit will fail.
* For example, the {@link Handler#sendMessage(Message)} method will return false.
* </p><p class="note">
* Using this method may be unsafe because some messages may not be delivered
* before the looper terminates. Consider using {@link #quitSafely} instead to ensure
* that all pending work is completed in an orderly manner.
* </p>
*
* @see #quitSafely
*/
public void quit() {
mQueue.quit(false);
}
/**
* Quits the looper safely.
* <p>
* Causes the {@link #loop} method to terminate as soon as all remaining messages
* in the message queue that are already due to be delivered have been handled.
* However pending delayed messages with due times in the future will not be
* delivered before the loop terminates.
* </p><p>
* Any attempt to post messages to the queue after the looper is asked to quit will fail.
* For example, the {@link Handler#sendMessage(Message)} method will return false.
* </p>
*/
public void quitSafely() {
mQueue.quit(true);
}
7.Handler
7.1 消發(fā)送息
- Handler 發(fā)送消息最后都是執(zhí)行 enqueueMessage() 。
enqueueMessage - 這就做了 Message 的 target 指向 handler 自己。
- 消息入隊(duì)。
- mAsynchronous 默認(rèn)就是false , 構(gòu)造方法我們基本也不會(huì)去動(dòng)這參數(shù),默認(rèn)handler 是同步的。
private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
long uptimeMillis) {
//消息的target就是handler
msg.target = this;
msg.workSourceUid = ThreadLocalWorkSource.getUid();
//設(shè)置異步
if (mAsynchronous) {
msg.setAsynchronous(true);
}
//消息入隊(duì)
return queue.enqueueMessage(msg, uptimeMillis);
}
7.2 處理消息
- Looper.loop() 里面 msg.target.dispatchMessage(msg); 就是讓 Handler 處理消息。
- 這里可以看到三種,第一種是 Handler 發(fā)送消息用的 post , 就會(huì)把 Callback 封裝到 Message ,走 Message 自己的 Callback 。
- 第二種是Handler 創(chuàng)建時(shí),重寫了 Callback,這是有返回值得,如果為 true ,就會(huì)再執(zhí)行下面的 handleMessage 方法。
- 第三種就是沒(méi)傳 Callback ,就執(zhí)行 Handler 自己的 handleMessage ,但要重寫該方法。
/**
* Handle system messages here.
*/
public void dispatchMessage(@NonNull Message msg) {
//Message 內(nèi)部的callback,就是Handler,post()方法封裝在Message內(nèi)部的
if (msg.callback != null) {
handleCallback(msg);
} else {
//如果Handler創(chuàng)建時(shí)傳Callback就執(zhí)行這里
if (mCallback != null) {
//如果返回值為false 就結(jié)束
if (mCallback.handleMessage(msg)) {
return;
}
}
//如果mCallback為null,或者上面返回值為true,就執(zhí)行這里
handleMessage(msg);
}
}
/**
* Message 內(nèi)部的callback,就是Handler,post()方法封裝在Message內(nèi)部的
*/
private static void handleCallback(Message message) {
message.callback.run();
}
/**
* 創(chuàng)建時(shí)如果傳Callback,就執(zhí)行
*/
public interface Callback {
/**
* @param msg A {@link android.os.Message Message} object
* @return True if no further handling is desired
*/
boolean handleMessage(@NonNull Message msg);
}
/**
* 創(chuàng)建時(shí)如果沒(méi)傳Callback,而是重寫了該方法
*/
public void handleMessage(@NonNull Message msg) {
}
8.內(nèi)存泄漏
- 面試的時(shí)候賊喜歡問(wèn)這個(gè)問(wèn)題?。。?/li>
- 轉(zhuǎn) 小題大做 | 內(nèi)存泄漏簡(jiǎn)單問(wèn),你能答對(duì)嗎
9.HandlerThread
- HandlerThread 是谷歌封裝好 Looper 的 Thread ,子線程如果需要Handler推薦使用。
- 這里就是保證在使用Handler之前,Looper 一定準(zhǔn)備好。
public class HandlerThread extends Thread {
int mPriority;
int mTid = -1;
Looper mLooper;
private @Nullable Handler mHandler;
public HandlerThread(String name) {
super(name);
mPriority = Process.THREAD_PRIORITY_DEFAULT;
}
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
//獲得鎖創(chuàng)建looper
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
/**
* This method returns the Looper associated with this thread. If this thread not been started
* or for any reason isAlive() returns false, this method will return null. If this thread
* has been started, this method will block until the looper has been initialized.
* @return The looper.
*/
public Looper getLooper() {
if (!isAlive()) {
return null;
}
// If the thread has been started, wait until the looper has been created.
synchronized (this) {
//如果線程存活而且looper為空,就等待讓出鎖,直到looper創(chuàng)建
while (isAlive() && mLooper == null) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
return mLooper;
}
}
參考文檔
文章寫完了,發(fā)現(xiàn)別人有更好的,想了想還是把自己寫的發(fā)出去吧。。。
Android消息機(jī)制1-Handler(Java層)
小題大做 | 內(nèi)存泄漏簡(jiǎn)單問(wèn),你能答對(duì)嗎
又又又又?jǐn)€了一個(gè)月的Android面試題