首页 技术 正文
技术 2022年11月14日
0 收藏 869 点赞 4,396 浏览 5084 个字

本篇主要介绍Android中的消息机制,即Looper、Handler是如何协同工作的;

Looper:主要用来管理当前线程的消息队列,每个线程只能有一个Looper

Handler:用来将消息(Message)插入到当前线程的消息队列,并负责分发Looper中的消息,将消息发送到当前线程执行

具体关系图如下所示:

Android消息机制源码分析

接下来我们来分析一下Looper和Handler的源码,了解一下其中的奥妙。

首先我们从一个程序运行的入口来分析,源码如下:

public static void main(String[] args){    ......
Looper.prepareMainLooper();//初始化Looper ......
if(smainThreadHandler==null){
smainThreadHandler=thread.getHandler();//初始化Handler
} ...... Looper.loop();//消息循环执行
}

可以看出,程序在运行的时候首先会创建主线程的Looper对象,并通过Looper开启消息循环,不停的取出消息并执行;

接下来我们来研究Looper的源码;

第一部分:Looper源码

初始化

  private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
} 初始化Looper对象(该过程包含初始化消息队列和当前线程对象)
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));
}

可以看出Looper在初始化的时候,首先会创建消息队列,并通过sThreadLocal保存在当前的线程本地变量中;

再来看一下程序入口Looper.prepareMainLooper();//初始化Looper究竟执行了什么

 //初始化主线程的Looper对象
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}

这里有两行关键的代码:prepare(false);和sMainLooper = myLooper();

首先我们来看prepare(false);即上面讲到的 初始化Looper,可以看看上面的源码;

我们来看sMainLooper = myLooper();

  public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}

非常简单,我们上面提到在初始化Looper的时候会把Looper保存到当前线程的本地变量中,而这行代码的意思

就是从线程本地变量中将looper取出来

有了Looper,程序怎样才能运行?答案就在Looper.loop();//消息循环执行

  public static void loop() {
final Looper me = myLooper();//得到当前线程的Looper对象
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue;//得到消息队列 ...... //执行消息循环
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
msg.target.dispatchMessage(msg);
msg.recycleUnchecked();
}
}

显而易见,loop方法就是获取到当前线程的Looper对象,并从中循环取出消息,并执行,程序就这样跑起来了,具体是如何分发消息的

我们将会在下面讲解;

至此我们至少应该明白,当主线程在执行的时候

1、初始化Looper,并将Looper保存的线程变量中

2、Looper在初始化的时候会创建消息队列,并管理消息队列

2、取出Looper,并从消息队列中取出消息,循环执行

第二部分:Handler源码

我们知道Handler有两种使用方式,一种是使用handler.post(Runnable r);另一种是复写handleMessage(Message msg)方法

复写handleMessage(Message msg)方法非常简单,Handler在消息分发的时候,直接回调该方法即可,我们主要来研究第一种

 public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}

看到这个我们首先得明白getPostMessage(r)干了什么

 private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}

可以看出是将r封装成了一个消息,r作为该消息的回调;

我们接着看:

 public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}

关键代码在sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);

继续:

 //得到消息队列
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, msg, uptimeMillis);

 //handler和msg建立关联
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;这里将msg的target指向自己,msg的target只能是this
最后相信大家也看出来了,接下来就是真正将msg插入到消息队列了
 //负责将msg插入到消息队列
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
} synchronized (this) {
//将msg插入到消息队列 msg.when = when;
Message p = mMessages;
boolean needWake;
//消息队列为链式存储 如果消息队列中的消息为0,将msg插入到第一个,并新建一个message对象,将
//msg对象的next指向新建的message 等待新msg插入
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 {
//将msg插入到队尾
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;
} }
return true;
}

绕了这么大一圈,最后是通过Handler中的消息队列,将消息成功插入队尾,至此handler在post的时候实际上

是将r封装成了一个msg并插入到消息队列;

另外这里再提一下Handler第二种方式即复写handleMessage(Message msg)方法使用

handler.sendMessage(msg);

其源代码其实就是执行以上的

 public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}

重复以上一系列过程,将msg插入到消息队列;

最后我们来看一下比较关键的消息分发,消息分发是在以上Looper源码的loop方法中核心方法是:

msg.target.dispatchMessage(msg);

我们知道msg的target只能是Handler本身,因此消息分发是在Handler中来完成的;

   /**
* 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);
}
}

第一:if (msg.callback != null)  如果你传入了callback即Runnable,那么就执行 handleCallback(msg);

即调用r的run方法,通常是handler.post(r);类型的

第二:if (mCallback != null)这种方法允许让activity等来实现Handler.Callback接口,避免了自己编写handler重写handleMessage方法。

第三:handleMessage(msg); 即handler.sendMessage(msg);时调用的。直接回调Handler的handleMessage(msg);方法

至此,Android中的消息机制Looper和Handler相信你已经有了一定的了解;

最后我们再来总结一下

1、Looper 一个线程中只能有一个Looper,用来管理消息队列

2、Looper从消息队列里取出msg,交给Handler来进行分发,分发到Handler所在的线程执行,即创建Handler时的线程;

3、可以在当前线程中创建消息对象或直接复写Runnable的run方法,同过Handler将msg和r封装后的msg插入到消息队列

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,031
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,520
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,368
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,148
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,781
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,862