构造方法:
MessageQueue(boolean quitAllowed) {
/*通过构造方法制定是否允退出,供将来使用*/
mQuitAllowed = quitAllowed;
/*调用native借口,本质上创建一个NativeMessageQueue c++对象,并将对象的引用返回*/
mPtr = nativeInit();
}
nativeInit方法:
static jint 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<jint>(nativeMessageQueue);
}
析构方法:
对象销毁时,该方法被自动调用。主要是通过native方法销毁之前案创建的nativeMessageQueue方法:
protected void finalize() throws Throwable {
try {
dispose();
} finally {
super.finalize();
}
}
private void dispose() {
if (mPtr != 0) {
nativeDestroy(mPtr);
mPtr = 0;
}
}
native方法nativeDestroy:
static void android_os_MessageQueue_nativeDestroy(JNIEnv* env, jclass clazz, jint ptr) {
NativeMessageQueue* nativeMessageQueue = reinterpret_cast<NativeMessageQueue*>(ptr);
nativeMessageQueue->decStrong(env);
}
退出方法:
通过此api方法,可以通知消息队列进行退出:
void quit(boolean safe) {
/*不允许退出,则抛出异常,该配置在构造方法中指定*/
if (!mQuitAllowed) {
throw new RuntimeException("Main thread not allowed to quit.");
}
synchronized (this) {
/*已经在推出中,不做重复操作*/
if (mQuitting) {
return;
}
/*置位退出中状态*/
mQuitting = true;
if (safe) {
/*安全退出,则删除并回收所有未来的消息*/
removeAllFutureMessagesLocked();
} else {
/*非安全退出删掉并回收所有消息*/
removeAllMessagesLocked();
}
/*调用native方法,实际底层就是向一个管道中写数据,以便唤醒looper*/
nativeWake(mPtr);
}
}
enqueueMessage方法:
该方法实现消息压入队列的操作:
这里主要是要理解唤醒的操作,如果队列为空或者是一个”紧急“的消息且队列是阻塞的,那么就要唤醒looper来提取消息,这个在后面的next方法中可以看到作用。如果,插入的消息前面还有其他消息,且这些消息是异步的,则不需要再唤醒哦,道理很容易理解:有比你还着急的消息正等待被处理,你就先安稳呆着吧。
boolean enqueueMessage(Message msg, long when) {
/*消息已经在用了,抛出异常*/
if (msg.isInUse()) {
throw

本文详细剖析了Android中的MessageQueue,包括构造方法、析构方法、退出方法、enqueueMessage消息入队、next方法消息提取、remove系列方法、isIdling判断空闲状态、hasMessages查询消息以及IdleHandler和同步屏障的使用,揭示了Android消息处理的核心机制。
最低0.47元/天 解锁文章
3338

被折叠的 条评论
为什么被折叠?



