有这样一个场景:
public class MainActivity extends AppCompatActivity {
private static final int DELAY_TIME = 1000 * 60 * 5;
private Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
//Todo-action
return true;
}
});
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
@Override
public void run() {
Message message = mHandler.obtainMessage();
message.arg1 = 1;
mHandler.sendMessageDelayed(message, DELAY_TIME);
}
}).start();
}
}
如果当用户进入当前Activity,并在
DELAY_TIME 前退出activity,这个activity是不会被回收的。那么产生内存泄漏的原因是什么?我们不放先探一探源码(个人随笔免得忘记,有错误欢迎指正)。
我们知道Handler两个主要作用1)、消息处理机制;2)多线程更新ui。那么Handler是如何实现消息的传递以及线程的切换呢?带着疑问我们去看下Handler类的构造函数(以在主线程中创建一个Handler默认构造函数为例):
public Handler() {
this(null, false);
}
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());
}
}
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
从构造函数中看到两个Handler的重要成员变量:Looper和MessageQueue的初始化。还发现Handler中的成员变量其实是Looper中的mQueue的引用,那Looper作用是什么呢?来看下面这段话:
这个是关于Looper
* Class used to run a message loop for a thread. Threads by default do
* not have a message loop associated with them; to create one, call
* {
@link
#prepare} in the thread that is to run the loop, and then
* {
@link
#loop} to have it process messages until the loop is stopped.
源码解释写的很清楚:Looper使用与为一个线程循环的处理消息。我们不妨来看看
Looper.
myLooper
()做了啥
Looper.java:
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
ThreadLocal.java:
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
这个方法做的工作是找到当前的线程,拿到当前线程对应的Looper。那这时候就有疑问了,我们在Handler中并没有做关于Looper的初始化,当前Looper的实力到底哪里来呢,这时候再看Looper的注释发现了这样一个例子:
Looper.java:
* <pre>
* class LooperThread extends Thread {
* public Handler mHandler;
*
* public void run() {
* Looper.prepare();
*
* mHandler = new Handler() {
* public void handleMessage(Message msg) {
* // process incoming messages here
* }
* };
*
* Looper.loop();
* }
* }</pre>
源码给出了Looper的使用例子,从例子中看到了两个关键的方法:Looper.prepare()和Looper.loop()。我们先来看下prepare():
Looper.java:
public static void prepare() {
prepare(true);
}
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));
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
ThreadLocal.java:
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
咦,这好像是我们疑问的答案,prepare主要工作是创建一个Looper对象,并保存在当前线程对应的ThreadLocal中。但是,我们好像没有找到有调用prepare()方法的地方啊,我们刚一直在提到一个词-当前线程。我们再回到注释给的例子,当前我们以主线程为例,结合当前Handler所在线程ActivityThread,在ActivityThread中的main方法发现了这样几行代码:
ActivityThread.java:
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
SamplingProfilerIntegration.start();
// CloseGuard defaults to true and can be quite spammy. We
// disable it here, but selectively enable it later (via
// StrictMode) on debug builds, but using DropBox, not logs.
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
// Set the reporter for event logging in libcore
EventLogger.setReporter(new EventLoggingReporter());
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
Process.setArgV0("<pre-initialized>");
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");
}
哈哈,get了,这就是我们要找的答案,在主线程中创建Handler,我们的Looper在Activity启动阶段已经被创建保存在当前线程的ThreadLocal中,已经对looper做了初始化。
搞明白了在哪里调用prepare()和loop方法以及prepare()方法的主要工作,我们接下来看看loop()方法的主要工作,还是看一段源码:
Looper.java:
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
public static void loop() {
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
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 (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
// This must be in a local variable, in case a UI event sets the logger
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
final long end;
try {
msg.target.dispatchMessage(msg);
end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (slowDispatchThresholdMs > 0) {
final long time = end - start;
if (time > slowDispatchThresholdMs) {
Slog.w(TAG, "Dispatch took " + time + "ms on "
+ Thread.currentThread().getName() + ", h=" +
msg.target + " cb=" + msg.callback + " msg=" + msg.what);
}
}
if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
// Make sure that during the course of dispatching the
// identity of the thread wasn't corrupted.
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf(TAG, "Thread identity changed from 0x"
+ Long.toHexString(ident) + " to 0x"
+ Long.toHexString(newIdent) + " while dispatching to "
+ msg.target.getClass().getName() + " "
+ msg.callback + " what=" + msg.what);
}
msg.recycleUnchecked();
}
}
loop()方法其实就是个死循环,不断的去遍历当前成员变量mQueue,如果没有消息就阻塞,如果有消息就循环对消息进行处理。在源码中看到了比较中号的一行代码:
msg.target.dispatchMessage(msg);
msg.target是什么鬼??咦,它既然是个Handler类型,是不是发现什么,来看看入口函数:
Handler.java:
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
....
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);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
通过上面几个方法我们找到想要的答案,target就是我们创建的Handler,msg.target.dispatchMessage(msg)自然是调用到Handler中的dispatchMessage()
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
在Handler中又调回了HandlerMessage()方法,这个方法很熟悉就不用介绍了吧。到这里Looper的消息处理过程就大概讲完了。不过还有点疑问,我们好像还不知道msg如何加入到Looper的队列中哈
我们再从入口跟下消息的发布过程:
Handler.java:
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
....
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);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
MessageQueue.java
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) {
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();
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
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.
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
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;
}
通过上面可以看到,在调用Handler发布一条消息其实就是往MessageQueue中根据特定规则加入一条消息,MessageQueue就是消息Msg的容器,looper中遍历到消息来临并对消息进行处理。
好了,在非主线程中,过程其实差不多,这里重复分析。
流程走完了,再回到之前的那个问题--那么产生内存泄漏的原因是什么呢?
通过上面流程我们不难知道当前内存泄漏原因:
1)、通过匿名内部类创建Handler,当前Handler持有外部类的引用;
2)、又当前Handler被Msg持有在消息队列中等待被Looper处理,Looper是ActivityThread持有的生命周期贯穿整个app的生命周期。
因此,如果上面这种情况,在activity突然退出,当前activity不会马上被回收,会发生短暂的内存泄漏问题。
好像大部分时候我们都是这样写啊,那要怎么改:
主要有两个方法:
1)、将Handler声明为static内部类的方式;
2)、自己创建一个Looper,让Looper保持和Handler所在类一样的生命周期。
至此,终。
有问题欢迎指正~