3.2 Android 消息机制 - TomeOkin/Learning-Notes GitHub Wiki
Android 的消息机制主要通过 Handler、MessageQueue、Looper 三者的相互作用实现的。这里,我们通过实例进行分析:
public class ThumbnailDownloader<T> extends HandlerThread {
private static final String TAG = "ThumbnailDownloader";
private static final int MESSAGE_DOWNLOAD = 0;
Handler mHandler;
Map<T, String> requestMap = Collections.synchronizedMap(new HashMap<T, String>());
Handler mResponseHandler;
Listener<T> mListener;
public interface Listener<T> {
void onThumbnailDownloaded(T target, Bitmap thumbnail);
}
public void setListener(Listener<T> listener) {
mListener = listener;
}
public ThumbnailDownloader(Handler responseHandler) {
super(TAG);
mResponseHandler = responseHandler;
}
@Override
protected void onLooperPrepared() {
mHandler = new Handler() {
@SuppressWarnings("unchecked")
@Override
public void handleMessage(Message msg) {
if (msg.what == MESSAGE_DOWNLOAD) {
T target = (T)msg.obj;
Log.i(TAG, "Got a request for url: " + requestMap.get(target));
handleRequest(target);
}
}
};
}
public void queueThumbnail(T target, String url) {
Log.i(TAG, "Got an URL: " + url);
requestMap.put(target, url);
mHandler.obtainMessage(MESSAGE_DOWNLOAD, target)
.sendToTarget();
}
private void handleRequest(final T target) {
try {
final String url = requestMap.get(target);
if (target == null) {
return;
}
byte[] bitmapBytes = new FlickrFetchr().getUrlBytes(url);
final Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapBytes, 0, bitmapBytes.length);
Log.i(TAG, "Bitmap created");
mResponseHandler.post(new Runnable() {
@Override
public void run() {
if (requestMap.get(target) != url) {
return;
}
requestMap.remove(target);
mListener.onThumbnailDownloaded(target, bitmap);
}
});
} catch (IOException ioe) {
Log.e(TAG, "Error downloading image", ioe);
}
}
public void clearQueue() {
mHandler.removeMessages(MESSAGE_DOWNLOAD);
requestMap.clear();
}
}
首先,Handler 的创建是有要求的。
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 实现类以内部类进行声明,那么它有可能会导致外部类不会被垃圾回收。这里,有两种情况:
- 如果 Handler 是在其他线程中使用 Looper 或者 MessageQueue,那么这是不会有问题的;
- 然而如果 Handler 是在主线程中使用 Looper 或者 MessageQueue,那就需要注意了。为了防止发生内存泄漏,需要将 Handler 实现类定义为静态类,并且在外部类中,使用 WeakReference 来存放 Handler 实例,Handler 实现类中对所有外部类成员的引用也都必须使用弱引用。这是因为主线程会先初始化好一个消息队列,因此该消息队列的存活的作用域包含了 Handler 所处环境的的上下文及其他的部分。而在其他的线程中,消息队列需要我们手动创建,消息队列的存活的作用域与 Handler 所处环境的的上下文是一样的,自然就不会发送内存泄漏。举个例子,比如我们有一些管理类,我们希望它们不会发生内存泄漏,那就使用 Application 的上下文去关联,由于 Application 的上下文已经最大了,也就没有内存泄漏的说法了。
- 需要先创建消息队列才能创建 Handler,由于主线程已经存在消息队列了,因此直接就可以创建 Handler。
同时,我们也看到在 HandlerThread 的 run() 方法:
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
在使用 Looper.prepare();
创建消息队列后,回调了方法 onLooperPrepared()
,之后使用 Looper.loop();
开始获取和处理消息。这就解释了为什么 mHandler 是在 onLooperPrepared()
中创建的。
Looper.prepare();
方法负责创建消息队列,代码:
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();
}
- 每一个 Looper 创建时,除了会存储当前线程的引用,还会创建一个新的
MessageQueue
,并设置是否允许结束消息队列。可以看到,主线程的消息队列是不允许结束的。
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
- 创建好的 Looper 会存放在
ThreadLocal
中,这就意味着,每个线程都会有一个独立的副本。另外,每个线程都只能有一个 Looper。
当执行 Looper.loop();
时,会先取出当前线程的消息队列,接着阻塞式地获取一个消息,只有当 queue.next()
的返回值为空,也即消息队列已经结束时才会退出。如果取出的消息不为空,则会通过 msg.target.dispatchMessage(msg)
进行消息的分发。这里 msg.target
指的是获取该 msg
的 Handler
。之后,消息会通过 msg.recycleUnchecked()
回收到消息池中。
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
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
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
msg.target.dispatchMessage(msg);
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();
}
}
不知是否从 msg.recycleUnchecked();
中看出写什么端倪?为什么消息的回收是这样子的?难道消息池隐藏在 Message 之中?
这里要从消息的获取谈起。
我们一般是使用 mHandler.obtainMessage(MESSAGE_DOWNLOAD, object)
来获取一个消息的。
public final Message obtainMessage(int what, Object obj) {
return Message.obtain(this, what, obj);
}
public static Message obtain(Handler h, int what, Object obj) {
Message m = obtain();
m.target = h;
m.what = what;
m.obj = obj;
return m;
}
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();
}
最终,消息从 Message obtain()
中获取的。第一次执行的时候,sPool
是空的,因此会构造一个新消息并返回。之后,如果我们有通过 Message.recycleUnchecked()
回收 Message,那么 sPool 就不为空了。
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 = -1;
when = 0;
target = null;
callback = null;
data = null;
synchronized (sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
如果 sPool 不为空,那么我们就会通过以下几句获得一个 Message。
Message m = sPool;
sPool = m.next;
m.next = null;
看出来了吧,实际上就是使用 Message.next 来关联 Message,通过堆栈的方式进行操作,由此组成了一个消息池。
消息池的大小默认是 50 个,回收时如果消息池满了,回收的 Message 就会清除引用后被丢弃。
在获取消息后,消息通过 Message 的 sendToTarget()
进行发送。
public void sendToTarget() {
target.sendMessage(this);
}
// 以下为 Handler 类的方法
public final boolean sendMessage(Message msg) {
return sendMessageDelayed(msg, 0);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis) {
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
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 的 enqueueMessage()
添加到消息队列中。
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;
}
添加到消息队列的消息必须是未被使用过的。消息队列中的消息含有时间信息,该时间由 SystemClock.uptimeMillis() + delayMillis
构成的。
在 Android 中有三种获得当前时刻时间的方式,如下,前两种是
android.os
包中:
-
SystemClock.uptimeMillis()
:指的是从系统开机开始,到当前时刻的时间,但不包括深度睡眠的时间。 -
SystemClock.elapsedRealtime()
:指的是从系统开机开始,到当前时刻的时间,包括深度睡眠的时间。 -
System.currentTimeMillis()
:从 1970 年 1 月 1 日到现在的时间。
另外,
AlarmManager
只支持currentTimeMillis
和elapsedRealtime
这两种方式。
Thread.sleep(millis)
,Object.wait(millis)
,SystemClock.sleep(millis)
和Handler
都是使用uptimeMills
。
回到 MessageQueue.next()
,由于消息队列是按执行的时间排序的,我们直接判断第一个消息是否可以开始执行了,如果不可以,则阻塞直到消息可以开始执行,返回该消息。
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();
}
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.
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();
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
// Process the quit message now that all pending messages have been handled.
if (mQuitting) {
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)) {
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);
}
// Run the idle handlers.
// 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);
}
}
}
// 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;
}
}
消息的分发是通过 msg.target.dispatchMessage(msg);
,注意到,消息是从当前线程的消息队列中取出的,也即在分发消息时,方法不再是在 Thread.start()
所开启的新线程中执行的,而是在 Handler 所创建的线程(虽然线程信息是存在于 Looper 中的,但在 Handler 创建时与 Looper 建立了关联)中执行的。当然,由于此处的 mHandler 是在 run() 中创建的,因此此处没有线程切换过程。而对于 mResponseHandler
,由于其是在主线程中创建的,因此,在 mHandler 消费消息时,对 mResponseHandler 执行的调用最终分发消息时是在主线程中执行。
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
当消息是使用 Handler.post(Runnable)
方式发出的,那么 msg.callback
就是该 Runnable
。而如果在创建 Handler 时,使用了带 Callback 版本的方法创建,那么就对应与 mCallback
。
-
Looper.prepare()
及Looper.prepareMainLooper()
:创建消息队列的相关操作,需要在 Handler 创建前执行。 -
Looper.loop()
:消息队列的运作。 -
Looper.myLooper()
:获取当前线程的 Looper。 -
Looper.getMainLooper()
: 获取主线程的 Looper。 -
Looper.myQueue()
:获取当前线程的消息队列。 -
looper.quit()
及looper.quitSafely()
:除主线程 Looper 不允许销毁外,其他线程的 Looper 在创建后需要手动销毁。我们通过该方法来间接销毁消息队列。
《The Busy Coders Guide to Android Development》
《Android Programming:The Big Nerd Ranch Guide》
《Android 开发艺术探索》
Android中的时间:currentTimeMillis,uptimeMillis,elapsedRealtime
Android消息机制的原理剖析—闭环总结 文末的图片,为避免 csdn 屏蔽引用,转存了一份