写在前面的话
提起安卓的消息机制,我们马上就会联想到Handler,而Handler在日常的开发中经常会用到,因此了解安卓的消息机制还是很有必要的,毕竟知己知彼,百战不殆。
所谓的消息机制,实质上是线程之间通信的一种机制。在平常的开发中,我们都知道子线程中不能更新UI,我们的做法就是在子线程要更新UI的地方通知主线程,让主线程完成UI的更新。
与消息机制相关的类
Handler
负责发送和接收消息
Message
消息的载体
MessageQueue
消息队列
Looper
负责循环消息队列
ThreadLocal<T>
线程内部数据存储类,ThreadLocal通过set方法存储数据,通过get方法获取数据。在消息机制中,就是通过它来存储每一个线程的Looper对象
public void set(T value) {
Thread currentThread = Thread.currentThread();
Values values = values(currentThread);
if (values == null) {
values = initializeValues(currentThread);
}
values.put(this, value);
}
public T get() {
// Optimized for the fast path.
Thread currentThread = Thread.currentThread();
Values values = values(currentThread);
if (values != null) {
Object[] table = values.table;
int index = hash & values.mask;
if (this.reference == table[index]) {
return (T) table[index + 1];
}
} else {
values = initializeValues(currentThread);
}
return (T) values.getAfterMiss(this);
}
消息机制具体流程
接下来,我就以子线程如何通知主线程更新UI这一例子来详细介绍一下安卓的消息机制。
1. 调用Looper.prepare方法
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();
}
由代码可知,在prepare方法中,会创建一个Looper对象,并且一个线程也只会创建一个。
同时在Looper的构造方法中,会创建一个消息队列,即MessageQueue。
2. 封装一条需要发送的消息
Message msg = Message.obtain();
msg.what = 0;
msg.obj= obj;
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();
}
创建消息,我们用obtain方法,该方法的原则是,如果消息池中有Message,则直接取出,没有才会新创建一个Message。
what,消息的标记,类型为int
obj,消息需要传递的对象,类型为Object
3. 调用Handler的 send或者post 的方法发送消息
3.1首先创建一个Handler对象mHandler
private Handler mHandler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
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;
}
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
在Handler的构造方法,我们可以看到,mHandler与Looper和消息队列建立了关联
3.2 调用send或者post方法
-
send
sendEmptyMessage(int what)
sendEmptyMessageDelayed(int what, long delayMillis)
sendEmptyMessageAtTime(int what, long uptimeMillis)
sendMessage(Message msg)
sendMessageDelayed(Message msg, long delayMillis)
sendMessageAtTime(Message msg, long uptimeMillis)
sendMessageAtFrontOfQueue(Message msg) -
post
post(Runnable r)
postDelayed(Runnable r, long delayMillis)
postAtTime(Runnable r, long uptimeMillis)
postAtTime(Runnable r, Object token, long uptimeMillis)
postAtFrontOfQueue(Runnable r)
经过查看post方法的源码,发现post方法实际上也是调用的send类的方法在发送消息,区别在于post方法的参数是Runnable。
下面是post方法相关的源码
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
看上面代码我们知道,post方法中传递的参数虽然不是Message,但最终传递的对象依然是Message,Runnable对象成为了这个消息的一个属性
通过对Handler源码的分析,发现除了sendMessageAtFrontOfQueue方法之外,其余任何send的相关方法,都经过层层包装走到了sendMessageAtTime方法中,我们来看看源码:
(实际上,sendMessageAtFrontOfQueue方法除了uptimeMillis为0外,和sendMessageAtTime 一模一样)
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);
}
此时,mHandler会将消息通过enqueueMessage方法,放入消息队列
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
msg.target = this,就相当于给该消息贴上了mHandler的标签(谁发送的消息,谁接收处理)
这里的enqueueMessage方法是MessageQueue的方法,在该方法中会将Message根据时间排序,放入到消息队列中。
4. 调用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.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();
}
}
在这个方法中,有一个for的死循环,不断地调用queue.next()方法,将Message从消息队列中取出
然后调用msg.target.dispatchMessage(msg)方法,msg.target实际上就是mHandler
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
分析这个方法,有两个分支handleCallback和handleMessage,回忆前面所说的send和post方法,当调用的是send类的方法时,明显走handleMessage这个分支,此时,子线程已经成功将消息传递至主线程,在这里我们就可以更新UI了
当调用的是post方法时,msg.callback就是Runnable对象,此时会走handleCallback分支
private static void handleCallback(Message message) {
message.callback.run();
}
此时调用了run方法,走到这,子线程也已经将消息成功传至主线程,在这里我们就可以更新UI了
总结一下
任何线程在用到Handler处理消息时,都需要经过上面说的4个步骤,缺一不可,具体代码如下
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();
}
}
一个线程只有一个Looper,一个消息队列
Handler在什么线程创建实例,这个Handler就属于该线程
顺便提一下在子线程中更新UI的方法
1.handler.sendMessage
2.handler.post
3.view.post
4.activity.runOnUiThread
view.post
public boolean post(Runnable action) {
final AttachInfo attachInfo = mAttachInfo;
if (attachInfo != null) {
return attachInfo.mHandler.post(action);
}
// Postpone the runnable until we know on which thread it needs to run.
// Assume that the runnable will be successfully placed after attach.
getRunQueue().post(action);
return true;
}
activity.runOnUiThread
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}
查看源码发现,实际上2,3,4的原理和1是一样的,都是利用Handler来发送消息。
有人会疑问,我们平时在用Handler解决子线程不能更新UI的问题时,只是在主线程中创建了一个Handler对象,然后在子线程用这个Handler对象发送了一个消息,最后在Handler的回调方法中成功更新了UI,并没有经过1和4两个步骤。实际上在主线程中,1和4两个步骤,系统已经帮我们做了,下面是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.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");
}
网友评论