AHandler AMessage ALooper消息机制-源码6.0.0以上
AHandler AMessage ALooper消息机制
AHandler是Android native层实现的一个异步消息机制,在这个机制中所有的处理都是异步的,将变量封装到一个消息AMessage结构体中,然后放到队列中去,后台专门有一个线程ALooper会从这个队列中取出消息然后分发执行,执行函数就是AHandler实例的onMessageReceived。
注意:本文中源码是基于Android11的,6.0以上都是相同的,6.0以下的源码略有不同
1.主要类
主要的涉及的有以下三个类
AMessage
消息类,用于构造消息,通过post方法投递出去给ALooperALooper
轮询类,用于保存消息队列,然后将消息发送到对应的AHandlerAHandler
处理类,用于实际消息的处理
2.消息类型
发送的消息按照是否需要答复,分为两种
- 普通消息
- 需答复消息
3.模型简介
普通消息被Post到消息队列,Looper不断的从队列中取出消息并分发给相应的Handler处理。如果是需答复消息的话使用PostAndAwaitResponse,Handler处理完以后通过postReply将消息返回给发送方,发送方通过新建的responsemsg接收。

4.代码分析
4.1 初始化
伪代码
sp<ALooper> looper = new ALooper;//创建一个ALooper实例
sp<AHandlerReflector> mHandler = new AHandlerReflector();//创建一个AHandler实例
looper->registerHandler(mHandler);//1. registerHandler会调用AHandler的setID方法将looper设置到Handler里面
looper->start(true);//2. 根据参数创建并启动LooperThread
代码追踪
- 注册mHandler到looper
ALooper.cpp
ALooper::handler_id ALooper::registerHandler(const sp<AHandler> &handler) {
return gLooperRoster.registerHandler(this, handler);
}
直接调用ALooperRoster的registerHandler,生成一个handler ID并保存起来
ALooperRoster.cpp
ALooper::handler_id ALooperRoster::registerHandler(
const sp<ALooper> &looper, const sp<AHandler> &handler) {
Mutex::Autolock autoLock(mLock);
if (handler->id() != 0) {
CHECK(!"A handler must only be registered once."); //一个handler在同一个looper中只能注册一次
return INVALID_OPERATION;
}
HandlerInfo info; //HandlerInfo 结构体,保存looper和handler,将其绑定在一起
info.mLooper = looper;
info.mHandler = handler;
ALooper::handler_id handlerID = mNextHandlerID++; //生成handler ID
mHandlers.add(handlerID, info); //mHandlers为ALooperRoster的私有,保存handler列表
handler->setID(handlerID, looper);
return handlerID;
}
- 启动looper循环
ALooper.cpp
status_t ALooper::start(
bool runOnCallingThread, bool canCallJava, int32_t priority) {
if (runOnCallingThread) {
{
Mutex::Autolock autoLock(mLock);
if (mThread != NULL || mRunningLocally) {
return INVALID_OPERATION;
}
mRunningLocally = true;
}
do {
} while (loop());
return OK;
}
Mutex::Autolock autoLock(mLock);
if (mThread != NULL || mRunningLocally) {
return INVALID_OPERATION;
}
mThread = new LooperThread(this, canCallJava);//开启一个线程
status_t err = mThread->run(
mName.empty() ? "ALooper" : mName.c_str(), priority);
if (err != OK) {
mThread.clear();
}
return err;
}

4.2 普通消息使用流程
- 实现一个
AHandler的子类,主要是onMessageReceived方法 - 创建一个
ALooper对象 - 创建消息
AMessage进行投递Post onMessageReceived方法得到调用,处理实际的事务
伪代码
发送
sp<AMessage> msg = new AMessage(kWhatSaySomething, mHandler); //在AMessage的构造方法里获取Ahandler对应的Looper并保存
msg->post(); //1. 发送消息
处理
AHandlerReflector:: onMessageReceived //消息的具体的处理实现
代码追踪
发送消息
AMessage.cpp
status_t AMessage::post(int64_t delayUs) {
sp<ALooper> looper = mLooper.promote();
if (looper == NULL) {
ALOGW("failed to post message as target looper for handler %d is gone.", mTarget);
return -ENOENT;
}
looper->post(this, delayUs); //进到looper线程
return OK;
}
ALooper.cpp
void ALooper::post(const sp<AMessage> &msg, int64_t delayUs) {
Mutex::Autolock autoLock(mLock);
int64_t whenUs;
if (delayUs > 0) {
whenUs = GetNowUs() + delayUs;
} else {
whenUs = GetNowUs();
}
List<Event>::iterator it = mEventQueue.begin();
while (it != mEventQueue.end() && (*it).mWhenUs <= whenUs) {
++it;
}
Event event;
event.mWhenUs = whenUs;
event.mMessage = msg;
if (it == mEventQueue.begin()) {
mQueueChangedCondition.signal(); //如果之前消息队列为空,没有event,loop是处于阻塞状态的,此处当有消息进入时,先通知looperthread启动
}
mEventQueue.insert(it, event); //进入消息队列
}
looper循环进行分发
ALooper.cpp
bool ALooper::loop() {
Event event;
{
Mutex::Autolock autoLock(mLock);
if (mThread == NULL && !mRunningLocally) {
return false;
}
if (mEventQueue.empty()) {
mQueueChangedCondition.wait(mLock); //如果消息队列为空,则等待,进入阻塞状态
return true;
}
int64_t whenUs = (*mEventQueue.begin()).mWhenUs;
int64_t nowUs = GetNowUs();
if (whenUs > nowUs) {
int64_t delayUs = whenUs - nowUs;
mQueueChangedCondition.waitRelative(mLock, delayUs * 1000ll);
return true;
}
event = *mEventQueue.begin(); //取出队列排头消息
mEventQueue.erase(mEventQueue.begin()); //退出消息队列
}
event.mMessage->deliver(); //根据每个消息携带的handler做转发处理
// NOTE: It's important to note that at this point our "ALooper" object
// may no longer exist (its final reference may have gone away while
// delivering the message). We have made sure, however, that loop()
// won't be called again.
return true;
}
返回工作线程
AMessage.cpp
void AMessage::deliver() {
sp<AHandler> handler = mHandler.promote();
if (handler == NULL) {
ALOGW("failed to deliver message as target handler %d is gone.", mTarget);
return;
}
handler->deliverMessage(this); //转发到相应的handler实例
}
转发到相应的Handler
void AHandler::deliverMessage(const sp<AMessage> &msg) {
onMessageReceived(msg);//Handler实例必须覆盖此方法,在这里做对应的处理,一般采用switch语句进行不同的处理
mMessageCounter++;
if (mVerboseStats) {
uint32_t what = msg->what();
ssize_t idx = mMessages.indexOfKey(what);
if (idx < 0) {
mMessages.add(what, 1);
} else {
mMessages.editValueAt(idx)++;
}
}
}

4.3 需要答复的消息使用流程
- 实现一个
AHandler的子类,主要是onMessageReceived方法 - 创建一个
ALooper对象 - 创建消息
AMessage进行投递PostAndAwaitResponse onMessageReceived方法得到调用,处理实际的事务- 处理完消息后发送答复
postReply - 发送端接收答复消息
response
伪代码
发送/接收答复
sp<AMessage> msg = new AMessage(kWhatSaySomething, mHandler); //发送的消息
sp<AMessage> responsemsg; //接收存储答复消息
msg->postAndAwaitResponse(responsemsg);
处理/答复
AHandlerReflector:: onMessageReceived //消息的具体的处理实现
sp<AReplyToken> replyID;
CHECK(msg->senderAwaitsResponse(&replyID));
sp<AMessage> response = new AMessage;//创建答复消息
response->postReply(replyID);//发送答复消息
代码追踪
AMessage.cpp
status_t AMessage::postAndAwaitResponse(sp<AMessage> *response) {
return gLooperRoster.postAndAwaitResponse(this, response);
}
AMessage.cpp
status_t AMessage::postAndAwaitResponse(sp<AMessage> *response) {
sp<ALooper> looper = mLooper.promote();
if (looper == NULL) {
ALOGW("failed to post message as target looper for handler %d is gone.", mTarget);
return -ENOENT;
}
sp<AReplyToken> token = looper->createReplyToken(); 创建Token标识,此token用来唯一的标识这条信息
if (token == NULL) {
ALOGE("failed to create reply token");
return -ENOMEM;
}
setObject("replyID", token); //将此token添加到该Message的replyID字段
looper->post(this, 0 /* delayUs */); //发给looper
return looper->awaitResponse(token, response); //在此处就阻塞住,不返回了
}
post过程和普通消息的一致,先发送到looper,然后loop分发给对应的handler处理,不同的是此处在mRepliesCondition.wait(mRepliesLock)阻塞等待
ALooper.cpp
status_t ALooper::awaitResponse(const sp<AReplyToken> &replyToken, sp<AMessage> *response) {
// return status in case we want to handle an interrupted wait
Mutex::Autolock autoLock(mRepliesLock);
CHECK(replyToken != NULL);
while (!replyToken->retrieveReply(response)) { //第一次会进入这个循环
{
Mutex::Autolock autoLock(mLock);
if (mThread == NULL) {
return -ENOENT;
}
}
mRepliesCondition.wait(mRepliesLock); //等待直到收到答复广播
}
return OK;
}
等收到mRepliesCondition.broadcast()以后,会执行retrieveReply,它的作用是将返回的reply拷贝到response
AReplyToken是一个结构体,定义在AMessage.h文件中
// if reply is not set, returns false; otherwise, it retrieves the reply and returns true
bool retrieveReply(sp<AMessage> *reply) {
if (mReplied) {
*reply = mReply;
mReply.clear();
}
return mReplied;
}
所以上面的程序就在等待mRepliesCondition.broadcast()的发出,而这个broadcast是在哪里发出了,我们接着看
接着看消息的处理,和普通消息一致,在相应的handler实例的onMessageReceived中得到处理,处理完以后创建答复消息
sp<AReplyToken> replyID;
CHECK(msg->senderAwaitsResponse(&replyID));
sp<AMessage> response = new AMessage;//创建答复消息
response->postReply(replyID);//发送答复消息
答复消息也是也AMessage的形式发出
AMessage.cpp
status_t AMessage::postReply(const sp<AReplyToken> &replyToken) {
if (replyToken == NULL) {
ALOGW("failed to post reply to a NULL token");
return -ENOENT;
}
sp<ALooper> looper = replyToken->getLooper();//根据replyToken获取消息所在的looper
if (looper == NULL) {
ALOGW("failed to post reply as target looper is gone.");
return -ENOENT;
}
return looper->postReply(replyToken, this); //转到looper
}
在looper这里首先将reply消息拷贝的位于AReplyToken的一个缓冲变量mReply,然后发出回复成果广播
ALooper.cpp
status_t ALooper::postReply(const sp<AReplyToken> &replyToken, const sp<AMessage> &reply) {
Mutex::Autolock autoLock(mRepliesLock);
status_t err = replyToken->setReply(reply); //将回复消息保存
if (err == OK) {
mRepliesCondition.broadcast(); /发出已回复广播
}
return err;
}
保存回复信息到缓存变量mReply
AMessage.cpp
status_t AReplyToken::setReply(const sp<AMessage> &reply) {
if (mReplied) {
ALOGE("trying to post a duplicate reply");
return -EBUSY;
}
CHECK(mReply == NULL);
mReply = reply; //保存回复信息
mReplied = true;
return OK;
}

参考:
AHandler AMessage ALooper消息机制
AHandler AMessage ALooper消息机制-源码6.0.0以上的更多相关文章
- Android Handler消息机制源码解析
好记性不如烂笔头,今天来分析一下Handler的源码实现 Handler机制是Android系统的基础,是多线程之间切换的基础.下面我们分析一下Handler的源码实现. Handler消息机制有4个 ...
- Android消息机制源码分析
本篇主要介绍Android中的消息机制,即Looper.Handler是如何协同工作的: Looper:主要用来管理当前线程的消息队列,每个线程只能有一个Looper Handler:用来将消息(Me ...
- [Android]简略的Android消息机制源码分析
相关源码 framework/base/core/java/andorid/os/Handler.java framework/base/core/java/andorid/os/Looper.jav ...
- 史上最详细的Android消息机制源码解析
本人只是Android菜鸡一个,写技术文章只是为了总结自己最近学习到的知识,从来不敢为人师,如果里面有不正确的地方请大家尽情指出,谢谢! 606页Android最新面试题含答案,有兴趣可以点击获取. ...
- Android事件分发机制源码分析
Android事件分发机制源码分析 Android事件分发机制源码分析 Part1事件来源以及传递顺序 Activity分发事件源码 PhoneWindow分发事件源码 小结 Part2ViewGro ...
- Springboot学习04-默认错误页面加载机制源码分析
Springboot学习04-默认错误页面加载机制源码分析 前沿 希望通过本文的学习,对错误页面的加载机制有这更神的理解 正文 1-Springboot错误页面展示 2-Springboot默认错误处 ...
- 阿里云视频直播API签名机制源码
阿里云视频直播API签名机制源码 本文展示:通过代码实现下阿里视频直播签名处理规则 阿里云视频直播签名机制,官方文档链接:https://help.aliyun.com/document_detail ...
- ApplicationEvent事件机制源码分析
<spring扩展点之三:Spring 的监听事件 ApplicationListener 和 ApplicationEvent 用法,在spring启动后做些事情> <服务网关zu ...
- 【转】Win 7 下源码运行OpenERP7.0
原文地址:Win 7 下源码运行OpenERP7.0 安装Python2.7 下载地址:http://www.python.org/getit/注:OpenERP7.0支持的Python版本最高为2. ...
- CentOS7源码安装Redis5.0.4非关系型数据库
源码安装redis-5.0.4 一. 下载redis 1. 需要连接网络 二. 案例(另一种安装方法) [root@localhost ~]# wget http://download.redis.i ...
随机推荐
- 高可用linux 服务器搭建
最原始的服务部署,为单点部署,即直接把服务部署在一个服务器上.如果服务器出现故障,或者服务因为某个异常而挂掉,则服务就会发生中断.单点部署出现故障的概率最高. 后来,出现了网关,比如 nginx ko ...
- HBase-通过外部表将Hive数据写入到HBase
a) 准备测试数据 这里准备的csv文件data_test.csv,内容没用''包裹,逗号作为列分隔符 171301,燕青,男,27,发展部 171207,武松,男,39,开发部 171307,李逵, ...
- NC21125 践踏
题目链接 题目 题目描述 首先给定一个定值k,支持如下操作(在数轴上) 加入一条线段[l,r] 删除一条已经存在的线段 给定x,问有多少个区间包含x+kt,其中t是一个整数变量,即t ∈ Z 比如说当 ...
- 解锁Mysql中的JSON数据类型,怎一个爽字了得
引言 在实际业务开发中,随着业务的变化,数据的复杂性和多样性不断增加.传统的关系型数据库模型在这种情况下会显得受限,因为它们需要预先定义严格的数据模式,并且通常只能存储具有相同结构的数据.而面对非结构 ...
- Laravel入坑指南(6)——Redis缓存
写在前面: Redis是常用nosql服务之一,在Redis官网上最新的稳定版本是6.0.6.这里不讨论Redis服务如何编译,如何使用.在Redis官网有很健全的文档. 这里要讨论的是无论在cent ...
- linux删除目录下指定文件方法
1.删除当前目录下文件名含有2013的文件 ls | grep 2013 | xargs rm --To be continue...
- virtualbox安装oracle linux后找不到eth0
用VirtualBox装oracle linux, ifconfig发现没有eth0: 按照以下步骤操作: 1 用ifconfig eth0 up启动网卡(默认未开启),执行ifconfig下看到et ...
- [BUUCTF][Web][ACTF2020 新生赛]Exec 1
打开靶机对应url 显示可以输出ip 来进行ping操作 尝试试一下是否有命令注入的可能 127.0.0.1|ls 果然可以,输出结果 index.php PING 127.0.0.1 (127.0. ...
- oracle不等于1怎么查?
空值null比较特殊,它不能通过=或者<>进行查询,只能用is null或者is not null进行查询,例如你的数据中有null值,那么用 字段名=1,字段名<>1,字段名 ...
- 【Azure APIM】验证APIM删除后的恢复步骤
问题描述 在Azure门户中,误删除API Management资源后,怎么办? 问题解答 遇见误删除的第一反应就是: 想恢复删除的内容,但是从门户上查看没有发现有可以操作的方面. (错误,Azure ...