Handler可以理解為線(xiàn)程間收發(fā)消息的處理器。在Android中最常見(jiàn)的應(yīng)用場(chǎng)景是子線(xiàn)程使用主線(xiàn)程的Handler發(fā)送消息,切換回主線(xiàn)程接收消息并處理消息。
Handler是怎么實(shí)現(xiàn)消息的收發(fā)的呢
Handler的實(shí)現(xiàn)主要需要與Looper、MessageQuere、Message一起實(shí)現(xiàn),它們的關(guān)系如下圖所示:

上圖含括了消息的收發(fā)的大致流程,Looper用于線(xiàn)程循環(huán)處理消息處理機(jī)制;MessageQuere是緩存消息的隊(duì)列;Message是消息類(lèi),其核心是消息回收復(fù)用機(jī)制;Handler消息的發(fā)送和接收處理器。下面我們從源碼的角度去剖析這幾個(gè)類(lèi)。
Looper
Looper是用于線(xiàn)程循環(huán)處理消息處理機(jī)制,如果需要在線(xiàn)程中實(shí)現(xiàn)Handler的消息機(jī)制,需要在線(xiàn)程中實(shí)現(xiàn)Looper的初始化和調(diào)用loop方法循環(huán)調(diào)度消息。我們平常在使用Handler時(shí),并沒(méi)有對(duì)Looper進(jìn)行初始化和調(diào)用loop,那是因?yàn)閱?dòng)應(yīng)用時(shí),framework已經(jīng)在主線(xiàn)程實(shí)現(xiàn)了,所以如果要在子線(xiàn)程做實(shí)現(xiàn)Handler機(jī)制,必須要在子線(xiàn)程對(duì)Looper進(jìn)行初始化和調(diào)用loop,以下是子線(xiàn)程實(shí)現(xiàn)Looper的代碼模板(Looper的注釋中有說(shuō)明):
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
//初始化Looper
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
//調(diào)用loop方法循環(huán)處理消息
Looper.loop();
}
我們看下Looper的初始化prepare方法的實(shí)現(xiàn)代碼:
//子線(xiàn)程的初始化
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
//當(dāng)前線(xiàn)程已經(jīng)創(chuàng)建Looper,一個(gè)線(xiàn)程不能重復(fù)創(chuàng)建Looper并初始化
throw new RuntimeException("Only one Looper may be created per thread");
}
//創(chuàng)建Looper并放入ThreadLocal與當(dāng)前線(xiàn)程進(jìn)行綁定
sThreadLocal.set(new Looper(quitAllowed));
}
//主線(xiàn)程的初始化
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
private Looper(boolean quitAllowed) {
//quitAllowed表示消息隊(duì)列是否可以釋放
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
Looper的初始化是通過(guò)prepare方法實(shí)現(xiàn),prepare有兩個(gè)主要的重載,一個(gè)是為子線(xiàn)程準(zhǔn)備,一個(gè)為為主線(xiàn)程,區(qū)別是:子線(xiàn)程的消息隊(duì)列可以釋放,而主線(xiàn)程的消息隊(duì)列不能釋放。初始化時(shí)創(chuàng)建的Looper放在ThreadLocal與線(xiàn)程進(jìn)行綁定,所以一般我們判定線(xiàn)程是主線(xiàn)程還是子線(xiàn)程,主要還是通過(guò)Looper的進(jìn)行判斷:
public static Looper getMainLooper() {
synchronized (Looper.class) {
return sMainLooper;
}
}
public @NonNull Thread getThread() {
return mThread;
}
只要判斷Looper.getMainLooper().getThread() 是否與當(dāng)前線(xiàn)程相等就可以判斷當(dāng)前線(xiàn)程是否是主線(xiàn)程。
我們接著看下loop方法:
public static void loop() {
final Looper me = myLooper();
if (me == null) {
//校驗(yàn)是否已經(jīng)初始化
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
//消息隊(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();
for (;;) {
//從消息隊(duì)列中獲取下一個(gè)需要處理的消息
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
//.....
try {
//調(diào)用msg的target(即Handler)分發(fā)消息
msg.target.dispatchMessage(msg);
// .....
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
//....
//釋放消息,并嘗試放入回收池中緩存復(fù)用
msg.recycleUnchecked();
}
}
loop方法采用死循環(huán)不停的從消息隊(duì)列中取下一個(gè)待處理的消息,調(diào)用Handler分發(fā)消息,釋放消息類(lèi)并放入緩存復(fù)用池。這里不知大家是否有以下的疑問(wèn):
a、死循環(huán)不停的從消息隊(duì)列中取消息不會(huì)很耗性能嗎?
b、如果消息隊(duì)列中已經(jīng)沒(méi)有待處理的消息,loop方法不就退出了嗎,那么后面線(xiàn)程再次有消息發(fā)送時(shí)怎么辦?
c、為什么需要將回收的消息類(lèi)放入池中并復(fù)用?
解答:
a、b:不會(huì)很耗性能,如果消息隊(duì)列為空時(shí),線(xiàn)程會(huì)掛起釋放CPU時(shí)間片,等到有新消息時(shí)才會(huì)喚醒繼續(xù)執(zhí)行(MessageQueue源碼分析會(huì)知道原因)
c:消息收發(fā)頻繁時(shí),就可以緩解創(chuàng)建消息類(lèi)的內(nèi)存和CPU開(kāi)銷(xiāo),可以提升性能
Message
消息類(lèi),它的核心是回收復(fù)用機(jī)制,我們看下它的源碼:
public final class Message implements Parcelable {
//消息事件編號(hào)
public int what;
//消息參數(shù)int類(lèi)型
public int arg1;
//消息參數(shù)int類(lèi)型
public int arg2;
//消息參數(shù)object類(lèi)型
public Object obj;
....
//標(biāo)識(shí)消息已經(jīng)被使用
/*package*/ static final int FLAG_IN_USE = 1 << 0;
/** If set message is asynchronous */
//標(biāo)識(shí)是異步消息
/*package*/ static final int FLAG_ASYNCHRONOUS = 1 << 1;
/** Flags to clear in the copyFrom method */
//copyFrom方法中要清除的標(biāo)志
/*package*/ static final int FLAGS_TO_CLEAR_ON_COPY_FROM = FLAG_IN_USE;
//消息標(biāo)識(shí)位
/*package*/ int flags;
//消息處理機(jī)時(shí)間戳
/*package*/ long when;
//消息參數(shù)Bundle類(lèi)型
/*package*/ Bundle data;
//消息處理器
/*package*/ Handler target;
//消息處理器
/*package*/ Runnable callback;
// sometimes we store linked lists of these things
//下一個(gè)待處理的消息
/*package*/ Message next;
//回收復(fù)用池同步鎖
private static final Object sPoolSync = new Object();
//回收復(fù)用池
private static Message sPool;
//回收復(fù)用池當(dāng)前大小
private static int sPoolSize = 0;
//回收復(fù)用池最大容量
private static final int MAX_POOL_SIZE = 50;
private static boolean gCheckRecycle = true;
/**
嘗試從回收復(fù)用池中復(fù)用被回收的消息類(lèi),如果池中沒(méi)有可復(fù)用的則創(chuàng)建一個(gè)新的消息
* 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) {
//從消息池中復(fù)用被回收的消息類(lèi)
Message m = sPool;
sPool = m.next;
m.next = null;
//將消息類(lèi)的標(biāo)識(shí)為清除已使用
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
//沒(méi)有可復(fù)用的則創(chuàng)建一個(gè)新的消息
return new Message();
}
......
/**
回收消息類(lèi)并嘗試放入回收復(fù)用池中
* Recycles a Message that may be in-use.
* Used internally by the MessageQueue and Looper when disposing of queued Messages.
*/
void recycleUnchecked() {
// Mark the message as in use while it remains in the recycled object pool.
// Clear out all other details.
//將標(biāo)志位標(biāo)識(shí)為已被使用
flags = FLAG_IN_USE;
//釋放相關(guān)資源
what = 0;
arg1 = 0;
arg2 = 0;
obj = null;
replyTo = null;
sendingUid = -1;
when = 0;
target = null;
callback = null;
data = null;
synchronized (sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {
//回收復(fù)用池沒(méi)有超過(guò)最大值則將被回收消息加入池中
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
.......
消息類(lèi)的回收復(fù)用池的容量是有限制的,代碼中限制為50,在頻繁發(fā)生消息時(shí)回收復(fù)用機(jī)制可以有效的減小內(nèi)存和CPU的開(kāi)銷(xiāo)
MessageQueue
消息隊(duì)列采用什么數(shù)據(jù)結(jié)構(gòu)呢?根據(jù)上面的Message類(lèi)可以知道:采用的是單鏈表,消息隊(duì)列的核心在于消息入隊(duì)和獲取下一個(gè)待處理的消息,我們主要針對(duì)這兩個(gè)源碼進(jìn)行解析:
//消息入隊(duì),Handler的sendMessage最終會(huì)調(diào)用MessageQueue的enqueueMessage方法,將消息加入消息隊(duì)列中
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
//如果消息的目標(biāo)處理器(即Handler)為空則拋出異常
throw new IllegalArgumentException("Message must have a target.");
}
if (msg.isInUse()) {
//如果消息已經(jīng)標(biāo)識(shí)為被使用則拋出異常
throw new IllegalStateException(msg + " This message is already in use.");
}
synchronized (this) {
if (mQuitting) {
//消息隊(duì)列是否中,則是否消息并退出
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)識(shí)為已被使用
msg.markInUse();
//設(shè)置何時(shí)處理消息
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
//如果消息隊(duì)列為空或者處理的時(shí)間為0(即立即處理)或者處理時(shí)間比消息隊(duì)列的隊(duì)頭的時(shí)間小
//則將消息設(shè)置為隊(duì)列的隊(duì)頭
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
//如果消息隊(duì)列不為空并且處理的時(shí)間不為0(即非立即處理)并且處理時(shí)間比消息隊(duì)列的隊(duì)頭的時(shí)間大
// 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;
//遍歷隊(duì)列,找到比消息處理時(shí)間大的消息(即找到要插入的位置)
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
//將消息插入比其處理時(shí)間大的前面
msg.next = p; // invariant: p == prev.next
prev.next = msg;
}
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
//調(diào)用native層喚醒被掛起的消息
nativeWake(mPtr);
}
}
return true;
}
//獲取下一個(gè)待處理的消息
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 (;;) {
//根據(jù)nextPollTimeoutMillis設(shè)置掛起時(shí)間
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) {
//找到下一個(gè)待處理的異步消息
// 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) {
//消息隊(duì)列不為空,有待處理的消息
if (now < msg.when) {
// Next message is not ready. Set a timeout to wake up when it is ready.
//當(dāng)前時(shí)間比消息處理時(shí)間小
//計(jì)算等待處理剩余時(shí)間
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// Got a message.
//當(dāng)前時(shí)間比消息處理時(shí)間大
//將消息出隊(duì)
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
//將消息標(biāo)識(shí)為已被使用
msg.markInUse();
//返回待處理的消息
return msg;
}
} else {
// No more messages.
//消息隊(duì)列為空
nextPollTimeoutMillis = -1;
}
// Process the quit message now that all pending messages have been handled.
if (mQuitting) {
//消息隊(duì)列已經(jīng)釋放,退出
dispose();
return null;
}
// If first time idle, then get the number of idlers to run.
// Idle handles only run if the queue is empty or if the first message
// in the queue (possibly a barrier) is due to be handled in the future.
//
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
//沒(méi)有空閑處理器并且消息隊(duì)列目前空閑,設(shè)置空閑處理器數(shù)量
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
// No idle handlers to run. Loop and wait some more.
//沒(méi)有空閑處理器,標(biāo)識(shí)為掛起消息隊(duì)列,并進(jìn)行下一次循環(huán)
mBlocked = true;
continue;
}
//有空閑處理器
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
//賦值空閑處理器
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
// Run the idle handlers.
// We only ever reach this code block during the first iteration.
//遍歷并執(zhí)行空閑處理器
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 {
//空閑處理器是否需要繼續(xù)保留
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}
if (!keep) {
//不保留空閑處理器
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
// Reset the idle handler count to 0 so we do not run them again.
pendingIdleHandlerCount = 0;
// While calling an idle handler, a new message could have been delivered
// so go back and look again for a pending message without waiting.
nextPollTimeoutMillis = 0;
}
}
MessageQueue入隊(duì)和出隊(duì)的源碼可以知道,消息隊(duì)列是有優(yōu)先級(jí)的那就是時(shí)間,時(shí)間小的排在隊(duì)列的前面,所以出隊(duì)從隊(duì)頭開(kāi)始取就可以了。消息入隊(duì)之后,隊(duì)列如果處于掛起狀態(tài)(mBlocked =true)則調(diào)用native層進(jìn)行喚醒。消息出隊(duì)時(shí)如果消息為空或者當(dāng)前時(shí)間比待處理的消息小則需要掛起,當(dāng)然也可以設(shè)置隊(duì)里空閑是的處理器(平常使用是沒(méi)有用到)。
Handler
Handler是消息收發(fā)處理器,我們來(lái)剖析下Handler的關(guān)鍵源碼:
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)前創(chuàng)建Handler所在線(xiàn)程的Looper
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
//獲取looper的消息隊(duì)列
mQueue = mLooper.mQueue;
//設(shè)置消息出去其
mCallback = callback;
//是否是異步
mAsynchronous = async;
}
public Handler(Looper looper, Callback callback, boolean async) {
//設(shè)置looper
mLooper = looper;
//使用looper的消息隊(duì)列
mQueue = looper.mQueue;
//設(shè)置消息處理器
mCallback = callback;
//是否是異步
mAsynchronous = async;
}
public static Handler getMain() {
//獲取主線(xiàn)程的handler
if (MAIN_THREAD_HANDLER == null) {
MAIN_THREAD_HANDLER = new Handler(Looper.getMainLooper());
}
return MAIN_THREAD_HANDLER;
}
public final Message obtainMessage()
{
//調(diào)用Message的obtain嘗試復(fù)用消息
return Message.obtain(this);
}
//發(fā)送消息:待立即處理的消息
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
//發(fā)送消息:延遲delayMillis時(shí)間處理消息
public final boolean postDelayed(Runnable r, long delayMillis)
{
return sendMessageDelayed(getPostMessage(r), delayMillis);
}
//獲取消息并設(shè)置消息處理器為runnable
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
//發(fā)送消息:待立即處理的消息
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
//發(fā)送消息:延遲delayMillis時(shí)間之后處理消息
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
//發(fā)送消息:在uptimeMillis時(shí)間點(diǎn)處理消息
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
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);
}
//將消息加入消息隊(duì)列中
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
//調(diào)用MessageQueue的enqueueMessage將消息加入隊(duì)列中
return queue.enqueueMessage(msg, uptimeMillis);
}
//分發(fā)消息
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
//如果消息有處理器(即Runnable),則調(diào)用消息的處理器
handleCallback(msg);
} else {
//消息沒(méi)有處理器
if (mCallback != null) {
//如果Handler有自定義處理器
//則調(diào)用Handler的自定義處理器
if (mCallback.handleMessage(msg)) {
//Handler的自定義處理器消耗了該消息,則完成消息處理
return;
}
}
/Handler沒(méi)有自定義處理器,或者Handler的自定義處理器沒(méi)有消耗該消息,則調(diào)用Handler的handleMessage處理消息
handleMessage(msg);
}
}
//調(diào)用消息的處理器(即Runnable)的run方法
private static void handleCallback(Message message) {
message.callback.run();
}
Handler發(fā)送消息其實(shí)調(diào)用的是MessageQueue的enqueueMessage方法將消息加入隊(duì)列中。分發(fā)消息時(shí)優(yōu)先使用消息的callback,再者是Handler的callback最后才是Handler的handleMessage。
結(jié)合上述代碼對(duì)消息機(jī)制的剖析,希望大家對(duì)其原理要理解透,不然比較容易不該出現(xiàn)的問(wèn)題。
對(duì)于Handler常遇到問(wèn)題及解答:
1、Handler是否可以在子線(xiàn)程中創(chuàng)建?如何在子線(xiàn)程中使用消息機(jī)制?
答:Handler是否可以在子線(xiàn)程中創(chuàng)建?——》可以在子線(xiàn)程中創(chuàng)建,前提是:a、在子線(xiàn)程中調(diào)用了Looper的prepare和loop,否則發(fā)送消息是會(huì)報(bào)錯(cuò)的,且不能處理UI相關(guān)的邏輯,因?yàn)槭撬鼘儆谧泳€(xiàn)程;b、創(chuàng)建時(shí)傳遞UI線(xiàn)程的Looper即mainLooper。如果要Handler處理UI邏輯只能在UI線(xiàn)程中創(chuàng)建或者創(chuàng)建時(shí)傳遞UI線(xiàn)程的Looper(即mainLooper)即可。
如何在子線(xiàn)程中使用消息機(jī)制?——》在子線(xiàn)程中調(diào)用Looper的prepare和loop
2、Handler send參數(shù)基本類(lèi)型和post有什么區(qū)別?如何選擇?
答:Handler sendMessage和post有什么區(qū)別?——》post會(huì)創(chuàng)建Message并調(diào)用sendMessage,send參數(shù)基本類(lèi)型也會(huì)先創(chuàng)建Message再調(diào)用重載發(fā)放進(jìn)行發(fā)送消息,兩者最終調(diào)用的都是MessageQueue的enqueueMessage方法;post的消息處理器是post參數(shù)的Runnable,而send參數(shù)基本類(lèi)型的消息處理器是Handler的callback或者h(yuǎn)andleMessage方法
如何選擇?——》個(gè)人認(rèn)為如果業(yè)務(wù)需要處理的消息種類(lèi)比較多建議或者傳遞額外參數(shù)用send方式比較好;如果業(yè)務(wù)消息種類(lèi)比較少不需要額外參數(shù)可以用post比較好
3、Android消息機(jī)制使用時(shí)如何較小內(nèi)存和CPU開(kāi)銷(xiāo)?
答:創(chuàng)建消息時(shí)用Handler.obtainMessage對(duì)消息進(jìn)行復(fù)用
4、Handler是否存在內(nèi)存泄漏問(wèn)題?如果有如何處理?
答:Handler是否存在內(nèi)存泄漏問(wèn)題?——》一般使用時(shí)會(huì)有,因?yàn)閯?chuàng)建的Handler時(shí)一般用重寫(xiě)dispatchMessage時(shí)或者傳遞了匿名的Runnable,匿名類(lèi)經(jīng)過(guò)jvm編譯之后內(nèi)部均持有外部類(lèi),這會(huì)導(dǎo)致外部類(lèi)生命周期以及結(jié)束,但由于匿名類(lèi)還持有外部類(lèi),而這個(gè)你們類(lèi)是被Message持有的,而Message被MessageQueue持有,而MessageQueue被Looper持有,就會(huì)導(dǎo)致外部類(lèi)得不到及時(shí)釋放,導(dǎo)致內(nèi)存泄漏,進(jìn)而會(huì)出現(xiàn)消息異步回調(diào)時(shí)程序崩潰的問(wèn)題。
如何處理?——》使用安全的Runnable和安全的Handler,下面是個(gè)人的處理方式代碼:
public abstract class SafeRunnable<T> extends SafeObject<T> implements Runnable {
public SafeRunnable(T pObject) {
super(pObject);
}
@Override
public void run() {
if(isDestroyed()){
return;
}
try {
safeRun();
}catch (Exception e){
e.printStackTrace();
}
}
public abstract void safeRun();
}
public abstract class SafeHandler<T> extends Handler {
private WeakReference<T> mReference;
public SafeHandler(T pObject){
mReference = new WeakReference<>(pObject);
}
public T getTargetReference(){
return mReference == null ? null : mReference.get();
}
public boolean isDestroyed(){
T targetObject = getTargetReference();
if(targetObject == null){
return true;
}else if(targetObject instanceof Activity){
return ((Activity) targetObject).isFinishing() || ((Activity) targetObject).isDestroyed();
}
return false;
}
@Override
public void handleMessage(Message msg) {
if(isDestroyed()){
return;
}
safeHandleMessage(msg);
}
public abstract void safeHandleMessage(Message msg);
}
public class SafeObject<T> {
private WeakReference<T> mReference;
public SafeObject(T pObject){
mReference = new WeakReference<>(pObject);
}
public T getReferenceTarget(){
T t = mReference == null ? null : mReference.get();
return t;
}
public void updateReference(T pReference){
mReference = new WeakReference<>(pReference);
}
public boolean isDestroyed(){
T obj = getReferenceTarget();
if(obj == null){
return true;
}
if(obj instanceof Activity){
if(((Activity) obj).isFinishing() || ((Activity) obj).isDestroyed()){
return true;
}
}else if(obj instanceof Fragment){
if(((Fragment) obj).isDetached()){
return true;
}
}else if(obj instanceof android.support.v4.app.Fragment){
if(((android.support.v4.app.Fragment) obj).isDetached()){
return true;
}
}
// Add begin by meitu.weiyx for CR:1010820
else if(obj instanceof View){
View view = (View) obj;
Context context = view.getContext();
if(context instanceof Activity){
if(((Activity) context).isFinishing() || ((Activity) context).isDestroyed()){
return true;
}
}
}
// Add end
return false;
}
public void destroy(){
mReference = null;
}
}
上述如有錯(cuò)誤之處,歡迎各位指正。