Android 消息机制,研究了两篇博客,和Android 的源码,总算是搞清楚了一些东西。
先用一张图,来大致清晰的显示一下,该篇博客所需展示的内容:
1.Android 中我们常常会写这样的代码:
private Handler mHandler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
//TODO 处理消息
}
}
};
以及这样的代码:
Message message=new Message();
message.what= WHAT;
message.obj= Model;
mHandler.sendMessage(message);
//或者
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
//线程去处理逻辑
}
}, 140);
接下来,就为大家解释上述代码,背后的秘密吧!不过在研究之前的先搞清楚以下几个问题?
首先,我们得清楚的知道,为什么要研究Android 消息机制?
- 为什么需要Android的消息机制
Android规定访问UI只能在主线程中进行。若在子线程中访问UI就会抛出异常。这个验证由ViewRootImpl的checkThread()来完成。
为什么不允许在非主线程访问UI呢?
这是因为Android的UI控件不是线程安全的。并且UI访问没有锁机制,并发访问会导致控件处于不可预期的状态。
那为什么不对UI访问加上锁机制呢?
(1)这显然会让UI访问的逻辑变得极其复杂;
(2)锁机制自然会降低效率;
(3)锁机制还会阻塞某些进程的执行。
但是Android又不建议在主线程进行耗时操作,因为这可能会引起ANR。
那么需要经过时间处理的逻辑才能影响UI结果的情况该如何处理呢?Android的消息机制应运而生。
Android的消息机制结构
Android的消息机制主要是指Handler的运行机制。Handler的运行需要底层MessageQueue和Looper的支撑。
MessageQueue: 采用以单链表为数据存储结构的消息列表。对外提供入队(enqueueMessage)和出队(next)工作。读取本身附带删除操作。单链表在插入和删除上比较有优势。
Looper: Handler在创建时会采用当前线程的Looper来构造消息循环系统。
Handler: 主要工作是消息的发送和接收。
了解了这两个问题之后,下面就可以开始对源码进行研究了:
- 先对Handler 的进行研究吧:
消息的发送可以使用Handler的post的方法(最终还是通过send方法完成)将一个Runnable投递到Looper中去处理。
handler.post(new Runnable(){
@Override
public void run() {
//do something
}});
或者这种用法的变形,用途很广,功能是延迟3秒后从欢迎界面进入主界面。这里并不是开启了一个新的线程。
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(SplashActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}, 3000);
看一下handler.post(Runnable callback)方法的,很明显最终还是通过send方法完成的。
public final boolean post(Runnable r) {
return sendMessageDelayed(getPostMessage(r), 0);
}
可以看到post 方法中的返回值,它又调用了一个方法getPostMessage(r); 主要是将Runnable 对象放到message 中的callback 属性中,然后返回一条空消息对象。
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
再看一下sendMessageDelayed的源码:
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
再看一下 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);
}
重点是: enqueueMessage() , 该方法内部会调用消息队列类(queue.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 ; 这行代码,就是将handler 对象引用又赋值到msg.target 变量中,为后面的消息处理埋下伏笔,伏笔就是还是这个Handler 来处理消息的,并没有另外的对象来处理。
这是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;
}
MessageQueue 中的出队方法的源码:
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;
}
}
现在来研究Looper 类,因为就是该类来将消息队列做循环驱动起来的
Looper 类中主要就是这两个方法:
Looper.prepare();
Looper.loop();
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
//保证一个thread 中只有一个looper 对象
throw new RuntimeException("Only one Looper may be created per thread");
}
// 添加一个looper对象
sThreadLocal.set(new Looper(quitAllowed));
}
/**
* 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() {
return sThreadLocal.get();
}
/**
* 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 traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
try {
//这就是之前埋下的伏笔,处理消息,dispatchMessage() , 还是msg.target这个之前存储的handler对象,然后重点就是处理消息,这个方法了
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();
}
}
MessageQueue 若有出队消息,则把这个消息,发给Looper ,交由Looper 中的loop() 方法处理,然后在loop()方法中,去调用msg.target.dispatchMessage(),而这个msg.targer就是之前入队消息时,传入的handler对象,而handler 是在主线程中创立的,所以处理消息,也会在主线程中执行。接下来就来看Handler 类中的dispatchMessage() 的源码了。
/**
* 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);
}
}
该方法,就是说,若有callback 对象实例,则处理handleCallback(),会去执行其中的线程中的run方法,主要是用于之前这种写法,因为在postDelayed()方法中,会将runnable 对象,转换成callback 对象。
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
//线程去处理逻辑
}
}, 140);
所以会直接执行线程中的run方法
private static void handleCallback(Message message) {
message.callback.run();
}
若不是这样,而是普通的sendMessage()消息的形式,这样的话,它就会执行handleMessage()方法,然而该方法就是我们使用handler 时,必须实现的处理消息方法,所以一切的逻辑都走完了。
/**
* Subclasses must implement this to receive messages.
*/
public void handleMessage(Message msg) {
}
最后再看看removeMessages()方法,还有许多移除消息的方法,可以ctrl+O 查看该类的方法,其他就不一一展示了。
/**
* Remove any pending posts of messages with code 'what' that are in the
* message queue.
*/
public final void removeMessages(int what) {
mQueue.removeMessages(this, what, null);
}
就是直接将消息队列中的该what标识的消息从其中移除。
时隔八个月再次写博客,手还是有点生,不过以后,我坚持每个星期至少一篇博客,来支撑自己的源代码底蕴!谢谢大家观看!