概述
线程间共享数据一般采用:全局变量方式、消息传递方式、参数传递方式等。
而在Android系统中采用最多的则是消息传递方式,也就是我们说的Android消息机制。Android消息机制设计的本意就是实现线程间通信。对于每个Android应用程序都运行在一个dalvik虚拟机进程中,应用进程开始的时候会启动一个主线程(MainThread),主线程负责处理和UI相关的事件,因此主线程通常又叫UI线程。而由于Android采用UI单线程模型,所以只能在主线程中对UI元素进行操作。并且主线程为我们提供了消息循环的机制,我们可以利用这个机制来实现线程间的通信。那么,我们就可以在非UI线程发送消息到UI线程,最终让UI线程来进行UI的操作。同时我们也可以实现子线程之间的通信,从而执行特定动作。但是当有多个后台任务时且异步任务的数据不太大时,我们自己创建消息循环来实现就有点复杂了,这时我们就可以使用Handler来完成了,由于主线程天然就具有消息循环机制,只需要创建Handler,重写handleMessage或者发送一个runnable即可。这就是我们为何要引入Handler消息机制。
那么什么是Handler机制?如何使用Handler机制?使用Handler机制常见问题有哪些?这是我们大家所关心的,所以本文后面会主要就这几个方面展开来讲解。
主要组成部分
在分析Handler消息机制之前首先了解一下它主要的组成部分:
Handler: 用来将消息发送到消息队列,对消息进行分发,并且对消息进行处理。
Looper: 一个线程可以产生一个Looper对象,由它来管理此线程里的MessageQueue。并且实现消息循环。
MessageQueue(消息队列):用来存放消息,并且与底层交互。
Message:消息对象,用来传递数据信息。
线程间通信
有A,B两个线程,我们可以在线程B中创建多个Handler,在线程A中用对应Handler的引用向消息队列(MessageQueue)中发送消息(Message)。线程B中的Looper会对MessageQueue进行管理,并且将消息从消息队列中取出,然后交由对应的Handler进行分发与处理,从而实现线程间通信。
主线程与子线程通信
在线程间通信中我们用的最多的就是在子线程中执行耗时任务,如查询数据库等,然后将执行结果发送到主线程中进行操作。首先我们在子线程中获得主线程的Looper对象,然后将执行结果封装成一个Message对象,通过Handler对象将其发送到主线程的消息队列中。主线程的Looper将消息从消息队列中取出,并在主线程中处理。
Android应用程序的消息处理机制是由消息循环、消息发送和消息处理这三个业务流程组成的,接下来,我们就详细描述这三个过程。
消息循环
消息循环的过程分为,创建消息循环过程与进入消息循环过程,下面我们就分析一下这两个过程: 消息循环是由Looper类来实现的,所以在讲应用程序进入消息循环之前我们应该首先分析一下应用程序是如何创建Looper对象的。我们可以通过调用Looper.prepare函数来为线程创建一个Looper对象,该函数定义在frameworks/base/core/java/android/os/Looper.java文件中:
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));
}
调用该函数时我们会创建一个Looper对象,这个Looper对象是存放在sThreadLocal成员变量里面的,成员变量sThreadLocal的类型为ThreadLocal,表示这是一个线程局部变量,保证每一个调用prepare的线程都有一个独立的Looper对象。我们在创建Looper的时候同时也会创建一个MessageQueue对象。后续的消息都会存放在该消息队列中,线程消息队列在Android应用程序消息处理机制中的作用比较重要,因此,我们看看它的构造函数的实现,代码定义在frameworks/base/core/java/android/os/MessageQueue.java文件中:
MessageQueue(boolean quitAllowed) {
mQuitAllowed = quitAllowed;
mPtr = nativeInit();
}
它的初始化工作是在JNI中实现的。在JNI中会创建一个NativeMessageQueue对象,然后会将该对象返回到Java层中记录,从而实现Java层与JNI层的交互。代码位置在frameworks/base/core/jni/android_os_MessageQueue.cpp
static jlong android_os_MessageQueue_nativeInit(JNIEnv* env, jclass clazz) {
NativeMessageQueue* nativeMessageQueue = new NativeMessageQueue();
if (!nativeMessageQueue) {
jniThrowRuntimeException(env, "Unable to allocate native queue");
return 0;
}
nativeMessageQueue->incStrong(env);
return reinterpret_cast<jlong>(nativeMessageQueue);
}
NativeMessageQueue::NativeMessageQueue() :
mPollEnv(NULL), mPollObj(NULL), mExceptionObj(NULL) {
mLooper = Looper::getForThread();
if (mLooper == NULL) {
mLooper = new Looper(false);
Looper::setForThread(mLooper);
}
}
NativeMessageQueue主要就是在内部创建了一个C++层的Looper对象。这个Looper对象主要作用是使应用程序线程进入睡眠等待状态;并且把应用程序线程唤醒。具体实现为它通过一个pipe函数来创建一个管道来实现进程间通信。管道就是一个文件,在管道的两端,分别是两个打开文件的文件描述符,这两个打开文件描述符都是对应同一个文件,其中一个是用来读的,另一个是用来写的,然后对文件描述符进行注册监听事件。一个线程通过读文件描述符来读管道的内容,当管道没有内容时,这个线程就会进入等待状态,而另外一个线程通过写文件描述符来向管道中写入内容,写入内容的时候,如果另一端正有线程正在等待管道中的内容,那么这个线程就会被唤醒。
C++层的Looper创建完成之后,这样,进入消息循环之前的准备工作就做完了,下面分析一下线程如何进入消息循环的。
上面的准备工作做完后我们可以调用Looper.loop函数使应用程序进入消息循环中。
/**
* 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(); //获取Looper对象
if (me == null) { //如果Looper为空就抛出异常
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue; //获取Looper中对应的MessageQueue
// 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
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
............................
try {
msg.target.dispatchMessage(msg); //分发给对应的Handler
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
.........................
msg.recycleUnchecked();
}
}
MessageQueue.java的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;
}
}
在该函数中通过不断调用MessageQueue对象的next函数,来从消息队列中获取消息,如果有消息需要处理就将消息返回交由对应的Handler处理;如果没有消息需要处理就会通过JNI调用C++层的Looper进行等待.
调用next函数的时候,有两种情况可能会让线程进入睡眠等待状态:
当消息队列中没有消息时,它会使线程进入等待状态。
消息队列中有消息,但是还没有到消息的指定时间,线程也会进入等待状态。
由于消息队列中的消息是按照执行时间先后进行排序的,所以我们可以根据消息的执行时间进行计算线程需要睡眠的时间。之后通过JNI调用C++层的Looper来监控是否有IO事件发生。
当发生了要监控的IO事件后,就会判断是否是我们所监控的管道发生所对应的事件。如果是我们监控的事件就说明应用程序中的消息队列里面有新的消息需要处理了,将Looper所在线程唤醒,之后就会将管道的内容读取出来,这样下一次进入睡眠等待时,知道自从上次处理完消息队列中的消息后,有没有新的消息加进来。
因为发送消息时将消息加入消息队列,会向这个管道写入新的内容来通知应用程序主线程有新的消息需要处理了,接下来我们就分析一下消息发送流程。
消息发送
应用程序进入消息循环后,我们可以调用Handler的成员函数sendMessageXXX发送消息。
在发送消息时我们可以为消息指定一个处理时间,如果没有指定时间默认为立即处理。最后我们将消息加入消息队列中。
同时,我们也可以通过postXXX函数发送一个Runnable对象,执行一个定时任务。
public final boolean sendMessage(Message msg) //通常调用该函数,默认delayed为0
{
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(); //获取一个message
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;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis); //重新计算时间,发送消息
}
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
MessageQueue queue = mQueue; //获取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); //将消息入队
}
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会将Runnable封装成一个消息,之后的流程就和发送一个Message的流程就相同了,最后都会将消息加入消息队列中。在把消息加入消息队列之前将当前的Handler赋值给消息的target变量,这样从队列中取出消息时才能找到所对应的Handler进行处理。
将消息加入消息队列时分为两种情况:
1.当队列为空,就会将新来的消息放入队头,此时如果Looper所在线程处于空闲等待中并唤醒Looper所在线程。
2.当队列不为空,此时Looper线程正在忙着处理消息,只用根据消息的处理时间在队列中找到一个合适的位置进行插入,如果插入位置不是队头,这时就不用唤醒Looper所在线程。
把消息加入到消息队列时,如果需要唤醒应用程序主线程,就需要调用JNI层函数来唤醒它了,最后通过打开文件描述符mWakeWritePipeFd往管道里写入一个字符串。因为我们在前面讲过如果消息队列没有消息时就会使Looper所在线程进入睡眠状态,最终等待管道中有内容可读的。并且我们已经注册了管道的监听事件,所以这个时候目标线程就会因为这个管道发生了一个事件而被唤醒,进行处理新的消息。
处理消息
消息从消息队列取出之后会调用消息的target成员变量的dispatchMessage函数进行分发消息。在发送消息时我们将当前的Handler对象赋值给了msg的target变量,一般就是通过哪个Handler来发送消息,就通过哪个Handler来处理消息。所以这时我们调用对应的Handler的dispatchMessage函数进行分发消息。这个函数定义在 frameworks/base/core/java/android/os/ Handler.java文件中。
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
Handler类的成员函数dispatchMessage按照以下顺序来分发一个消息:
前面讲过Handler调用postXXX函数发送一个Runnable对象时msg.callback不为空,之后handleCallback函数就会调用Runnable的run函数。
mCallback是Handler内部接口Callback的实现类的对象,一般为null。否则调用该接口的handleMessage函数。
如果前面两个条件都不满足,最后调用Handler的handleMessage,一般由子类重写。
小结
1.Android应用程序的消息处理机制由消息循环、消息发送和消息处理三个部分组成的。2.Android应用程序的主线程在进入消息循环过程前,会在内部创建一个Linux管道(Pipe),这个管道的作用是使得Android应用程序主线程在消息队列为空时可以进入空闲等待状态,并且使得当应用程序的消息队列有消息需要处理时唤醒应用程序的主线程。
3.Android应用程序的主线程进入空闲等待状态的方式实际上就是在管道的读端等待管道中有新的内容可读。
4.当往Android应用程序的消息队列中加入新的消息时,会同时往管道中的写端写入内容,通过这种方式就可以唤醒正在等待消息到来的应用程序主线程。
5.消息从消息队列中取出后,最后交由Handler进行分发处理。
Android源码中的应用
Handler消息机制在Android中的应用比较广泛。我们最熟悉的就是应用程序的启动过程中加载一个默认的Activity就是用到了Handler消息处理机制。该过程的实现主要在framework/base/core/java/android/app/ActivityThread.java文件中。
final H mH = new H();
mH是ActivityThread类的成员变量,H继承自Handler,所以mH也是一个Handler对象。创建该Handler对象的时候我们用的是无参的构造函数,所以ActivityThread主线程的Looper与mH绑定,即mH的消息都发送到ActivityThread主线程的消息队列中。
private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
if (DEBUG_MESSAGES) Slog.v(
TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
+ ": " + arg1 + " / " + obj);
Message msg = Message.obtain();
msg.what = what;
msg.obj = obj;
msg.arg1 = arg1;
msg.arg2 = arg2;
if (async) {
msg.setAsynchronous(true);
}
mH.sendMessage(msg);
}
在发送消息时首先获取一个Message对象,将参数封装进msg对象中,然后调用mH进行发送消息,没有时间参数默认立即处理。消息会被加入主线程的消息队列中。
private class H extends Handler {
public static final int LAUNCH_ACTIVITY = 100;
public static final int PAUSE_ACTIVITY = 101;
public static final int PAUSE_ACTIVITY_FINISHING= 102;
public static final int STOP_ACTIVITY_SHOW = 103;
public static final int STOP_ACTIVITY_HIDE = 104;
public static final int SHOW_WINDOW = 105;
public static final int HIDE_WINDOW = 106;
public static final int RESUME_ACTIVITY = 107;
public static final int SEND_RESULT = 108;
public static final int DESTROY_ACTIVITY = 109;
public static final int BIND_APPLICATION = 110;
public static final int EXIT_APPLICATION = 111;
public static final int NEW_INTENT = 112;
public static final int RECEIVER = 113;
public static final int CREATE_SERVICE = 114;
public static final int SERVICE_ARGS = 115;
public static final int STOP_SERVICE = 116;
............
public void handleMessage(Message msg) {
if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
switch (msg.what) {
case LAUNCH_ACTIVITY: {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
r.packageInfo = getPackageInfoNoCheck(
r.activityInfo.applicationInfo, r.compatInfo);
handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
} break;
case RELAUNCH_ACTIVITY: {
........
}
}
最后将消息从消息队列中取出来后,交由mH的handleMessage进行处理。
问题分析
构造Handler抛出异常
在新建线程中调用无参的Handler构造函数创建Handler,这时应用就会抛出异常。
因为新建的线程中没有Looper对象,而调用无参的Handler默认使用该线程的Looper对象,所以应用就会抛出异常。
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
1)根据抛出的异常我们知道,我们需要先调用Looper.prepare()创建一个Looper对象,然后再创建Handler对象。
2)最后可以通过Looper.loop(),实现消息循环。
消息阻塞
在使用Handler有时会遇到发送一个消息后,很长时间后才得到处理或者没有处理,其实底层相对来说还是比较稳定的,出现问题应该从自身找问题:1)当发生阻塞时一般是阻在了handleMessage中;
2)所以我们需要在我们应用的所有的handleMessage函数开始执行时输出log;
3)在结束执行时输出log,就可以定位出是哪里出现了问题;
4)最后对出问题的代码进行优化。