一、简介

Android的消息机制主要是指Handler的运行机制,那么什么是Handler的运行机制那?通俗的来讲就是,使用Handler将子线程的Message放入主线程的Messagequeue中,在主线程使用。
二、学习内容
学习Android的消息机制,我们需要先了解如下内容。
平常我们接触的大多是Handler和Message,今天就让我们来深入的了解一下他们。
三、代码详解
一般而言我们都是这样使用Handler的
xxHandler.sendEmptyMessage(xxx);
当然还有其他表示方法,但我们深入到源代码中,会发现,他们最终都调用了一个方法
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);
}
sendMessageAtTime()方法,但这依然不是结束,我们可以看到最后一句enqueueMessage(queue, msg, uptimeMillis);按字面意思来说插入一条消息,那么疑问来了,消息插入了哪里。
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。
虽然我们一般把他叫做消息队列,但是通过研究,我们发下,它实际上是一种单链表的数据结构,而我们对它的操作主要是插入和读取。
看代码33-44,学过数据结构,我们可以轻松的看出,这是一个单链表的插入末尾的操作。
这样就明白了,我们send方法实质就是向Messagequeue中插入这么一条消息,那么另一个问题随之而来,我们该如何处理这条消息。
处理消息我们离不开一个重要的,Looper。那么它在消息机制中又有什么样的作用那?
Looper扮演着消息循环的角色,具体而言它会不停的从MessageQueue中查看是否有新消息如果有新消息就会立刻处理,否则就已知阻塞在那里,现在让我们来看一下他的代码实现。
首先是构造方法
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
可以发现,它将当前线程对象保存了起来。我们继续
Looper在新线程创建过程中有两个重要的方法looper.prepare() looper.loop
new Thread(){
public void run(){
Looper.prepare();
Handler handler = new Handler();
Looper.loop();
}
}.start();
我们先来看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));
}
咦,我们可以看到这里面又有一个ThreadLocal类,我们在这简单了解一下,他的特性,set(),get()方法。
首先ThreadLocal是一个线程内部的数据存储类,通过它可以在指定的线程中存储数据,数据存储后,只有在制定线程中可以获取存储的数据,对于其他线程而言则无法获取到数据。简单的来说。套用一个列子:
private ThreadLocal<Boolean> mBooleanThreadLocal = new ThreadLocal<Boolean>();//
mBooleanThreadLocal.set(true);
Log.d(TAH,"Threadmain"+mBooleanThreadLocal.get());
new Thread("Thread#1"){
public void run(){
mBooleanThreadLocal.set(false);
Log.d(TAH,"Thread#1"+mBooleanThreadLocal.get());
};
}.start();
new Thread("Thread#2"){
public void run(){
Log.d(TAH,"Thread#2"+mBooleanThreadLocal.get());
};
}.start();
上面的代码运行后,我们会发现,每一个线程的值都是不同的,即使他们访问的是同意个ThreadLocal对象。
那么我们接下来会在之后分析源码,为什么他会不一样。现在我们跳回prepare()方法那一步,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
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
msg.target.dispatchMessage(msg);
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();
}
}
首先loop()方法,获得这个线程的Looper,若没有抛出异常。再获得新建的Messagequeue,在这里我们有必要补充一下Messagequeue的next()方法。
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;
}
}
从24-30我们可以看到,他遍历了整个queue找到msg,若是msg为null,我们可以看到50,他把nextPollTimeoutMillis = -1;实际上是等待enqueueMessage的nativeWake来唤醒。较深的源码涉及了native层代码,有兴趣可以研究一下。简单来说next()方法,在有消息是会返回这条消息,若没有,则阻塞在这里。
我们回到loop()方法27msg.target.dispatchMessage(msg);我们看代码
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
msg.target实际上就是发送这条消息的Handler,我们可以看到它将msg交给dispatchMessage(),最后调用了我们熟悉的方法handleMessage(msg);
三、总结
到目前为止,我们了解了android的消息机制流程,但它实际上还涉及了深层的native层方法.
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!
# Android
# 消息机制
# android异步消息机制 从源码层面解析(2)
# android异步消息机制 源码层面彻底解析(1)
# 代码分析Android消息机制
# Android异步消息机制详解
# android线程消息机制之Handler详解
# android利用消息机制获取网络图片
# Android 消息机制详解及实例代码
# Android消息机制Handler的工作过程详解
# 深入剖析Android消息机制原理
# Android 消息机制以及handler的内存泄露
# 从源码角度分析Android的消息机制
# 可以看到
# 这条
# 都是
# 在这里
# 数据结构
# 列子
# 它将
# 源代码
# 运行机制
# 的是
# 数据存储
# 是一个
# 链表
# 新消息
# 就会
# 来了
# 是一种
# 让我们
# 一句
# 在这
相关文章:
建站主机功能解析:服务器选择与快速搭建指南
视频网站app制作软件,有什么好的视频聊天网站或者软件?
如何通过云梦建站系统实现SEO快速优化?
视频网站制作教程,怎么样制作优酷网的小视频?
英语简历制作免费网站推荐,如何将简历翻译成英文?
佛山网站制作系统,佛山企业变更地址网上办理步骤?
武汉外贸网站制作公司,现在武汉外贸前景怎么样啊?
网站建设设计制作营销公司南阳,如何策划设计和建设网站?
制作宣传网站的软件,小红书可以宣传网站吗?
郑州企业网站制作公司,郑州招聘网站有哪些?
南京网站制作费用,南京远驱官方网站?
香港服务器网站测试全流程:性能评估、SEO加载与移动适配优化
建站之家VIP精选网站模板与SEO优化教程整合指南
已有域名和空间如何快速搭建网站?
建站主机与虚拟主机有何区别?如何选择最优方案?
宁波免费建站如何选择可靠模板与平台?
如何在Golang中实现微服务服务拆分_Golang微服务拆分与接口管理方法
安徽网站建设与外贸建站服务专业定制方案
宝塔建站教程:一键部署配置流程与SEO优化实战指南
如何在云主机快速搭建网站站点?
成都网站制作报价公司,成都工业用气开户费用?
网站广告牌制作方法,街上的广告牌,横幅,用PS还是其他软件做的?
定制建站模板如何实现SEO优化与智能系统配置?18字教程
哈尔滨网站建设策划,哈尔滨电工证查询网站?
专业网站制作企业网站,如何制作一个企业网站,建设网站的基本步骤有哪些?
如何选择域名并搭建高效网站?
如何在Golang中指定模块版本_使用go.mod控制版本号
建站之星体验版:智能建站系统+响应式设计,多端适配快速建站
建站之星如何防范黑客攻击与数据泄露?
如何在Golang中使用replace替换模块_指定本地或远程路径
沈阳个人网站制作公司,哪个网站能考到沈阳事业编招聘的信息?
西安制作网站公司有哪些,西安货运司机用的最多的app或者网站是什么?
济南网站制作的价格,历城一职专官方网站?
如何在阿里云购买域名并搭建网站?
微信h5制作网站有哪些,免费微信H5页面制作工具?
青岛网站设计制作公司,查询青岛招聘信息的网站有哪些?
建站一年半SEO优化实战指南:核心词挖掘与长尾流量提升策略
娃派WAP自助建站:免费模板+移动优化,快速打造专业网站
如何快速生成橙子建站落地页链接?
建站之星如何助力企业快速打造五合一网站?
网站制作免费,什么网站能看正片电影?
青浦网站制作公司有哪些,苹果官网发货地是哪里?
简历在线制作网站免费版,如何创建个人简历?
如何通过宝塔面板实现本地网站访问?
Swift开发中switch语句值绑定模式
黑客如何利用漏洞与弱口令入侵网站服务器?
网站建设制作需要多少钱费用,自己做一个网站要多少钱,模板一般多少钱?
制作无缝贴图网站有哪些,3dmax无缝贴图怎么调?
如何快速使用云服务器搭建个人网站?
如何通过商城免费建站系统源码自定义网站主题?
*请认真填写需求信息,我们会在24小时内与您取得联系。