首先呢,很多的博客都分析了Android的异步消息处理机制,我看了他们的分析之后,决定把自己所理解的也记录下来。
开始进入正题,大家都知道Android 的异步消息处理机制,并且大多数人都用来更新UI了。为了解决这个问题,可以在主线程中创建一个Handler的实例(为什么要在主线程中实例化,待会在下面会解答),在子线程中通过sendMessage将消息发送给Handler,然后在Handler的handleMessage中根据不同的消息处理不同的事情,这里就可以做更新UI了。
我们先看Handler的创建。一般情况下,大家创建Handler想必都是在主线程中创建的吧,这次我们在子线程中创建Handler并实例化,看看有什么问题。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
new Thread(new Runnable() {
@Override
public void run() {
Handler mHandler = new Handler();
}
}).start();
}
这段代码运行后,你会发现程序报错了,错误信息为: Can’t create handler inside thread that has not called Looper.prepare()。我们来看一看Handler的构造函数,会发现最终会调用它的Handler(Callback callback, boolean async),带有两个参数的构造函数。
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) {
//发现错误是这里抛出的
//于是我们发现,如果mLooper为空的话,就会抛出异常
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
我们来看看myLooper方法里面是什么。
/**
* 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() {
//返回的是Looper实例
return sThreadLocal.get();
}
那么sThreadLocal的get方法什么时候返回为空。什么时候不为空呢。上面给大家分析了,子线程中实例化Handler时,需要先调用Looper的prepare方法。这是为什么呢?我们来看看prepare方法,顺便分析一下原因。
//首先是这个方法,这个方法里面会调用下个方法
public static void prepare() {
prepare(true);
}
......
private static void prepare(boolean quitAllowed) {
//这里获取的是Looper的实例,一个线程只能有一个Looper对象,否则就会报错。
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
//就是在这里存放了Looper
//调用了Looper的构造函数,然后将Looper的引用存放在ThreadLocal里面(THreadLocal有点类似Map,存放的是键值对)
sThreadLocal.set(new Looper(quitAllowed));
}
......
//该方法里面得到了MessageQueue和当前线程的引用
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
所以大家也就知道了在子线程中实例化Handler需要先调用Looper的prepare方法。不然myLooper方法返回的就是空值。
经常使用Handler的同学可能会发现,为什么Handler在主线程实例化时不需要先调用Looper.prepare()呢?那就不得不提到一个很核心的类了,那就是ActivityThread类。ActivityThread是真正的核心类,它的main方法,是整个应用进程的入口。由于代码比较多,我只贴关键的。
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的一个方法
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");
}
可以看到在main方法里面调用了Looper.prepareMainLooper(),那我们再看看这个方法。
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
可以看到,同样是先调用prepare()方法,然后调用的myLooper()方法。是不是和子线程中的操作一样。只不过prepare()方法使我们手动操作,而myLooper方法是Handler构造函数里面调用的。
先小结一下,在主线程中实例化Handler不需要先调用Looper.prepare(),在子线程中实例化Handler需要先调用Looper.prepare()。
接下来我们看看如何发送消息以及接受消息,先看发送消息。
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
@Override
public void run() {
Message message = Message.obtain();
message.what = 1;
Bundle bundle = new Bundle();
bundle.putString("data", "hello");
message.setData(bundle);
handler.sendMessage(message);
}
}).start();
}
z这样就发送了一条消息。我们来分析一下,sendMessage把消息发到哪里去了,以及handleMessage是如何接收消息的。我们来通过源码来分析。我们会发现最终辗转调用到sendMessageAtTime()方法中。
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
//这个mQueue是在Handler的构造函数里面获得的,也就是Handler创建的时候获取,真正创建是在Looper的构造函数里面。因此一个Looper也就对应了一个MessageQueue。
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);
}
msg就是我们发送的msg对象,而uptimeMillis参数则表示发送消息时间,如果你调用的不是sendMessageDelayed()方法,延迟时间就为0,如果是,它的值等于自系统开机到当前时间的毫秒数再加上延迟时间。
接下来看enqueueMessage方法,这个方法最终会调用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;
//看到这里其实可以发现,MessageQueue并没有用集合将所有消息都保存起来,只是用mMessages表示当前待处理的消息,然后用时间将消息排序。
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;
}
这个方法内部是通过链表来操作的。发送消息就是发送到MessageQueue里面去了。接下来我们再来分析如何在MessageQueue里面取消息。这个就需要研究一下Looper.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 traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
try {
//这里的msg.target就是Handler对象,调用了dispatchMessage(msg)方法,将我们的消息发送出去
//这个msg就是我们发送的Message对象
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
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();
}
}
我们来看看dispatchMessage方法
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
首先判断mCallback不为空,则调用mCallback的handleMessage()方法,否则直接调用Handler的handleMessage()方法。接下来的你们都懂,嘿嘿。
好了讲了这么多,我们来总结一下。
首先,Handler将Message发送出去,然后保存在MessageQueue中,而Looper的loop方法不断从MessageQueue中取方法,然后再调用Handler的handleMessage方法。至此这就是整个流程。
接下来我们回答上面留的坑。
1.为什么要主线程中创建一个Handler的实例。
答:因为Handler总是依附于创建时所在的线程。所以创建Handler大多都是在主线程的。如果你在子线程中创建Handler,那你也就无法更新UI了。
最后小提示:创建Message对象时,最好使用Message.obtain()方法。这种方法性能更好,好在哪,我还在研究。嘿嘿。