1.快速复习

1.1 基本装置

装置名 作用 线程中数量
Looper 消息分发装置 从消息队列中取出一个消息,交给对应的Handler处理消息。 1
MessageQueue 消息队列 保存所有消息 1
Message 消息 封装通信数据 n
Handler 消息的发送和处理装置 处理消息,发送消息。 n

  每个想通信的线程都要安装上述装置,主线程默认已经安装。

1.2 基本工作流程

  Looper.prepare();

  Looper.loop();

  ...

  Hanlder.sendMessage(xxx);

  Hanlder.handleMessage(xxx);

  Looper.quit();

1.3 安装后两个线程间如何通信?

  线程B得到线程A中的hanlder5(一个线程中可有多个hanlder)后,就可用它向线程A发送消息,然后分发装置将该消息交给hanlder5处理。

2.Looper

  先分析这个是因为能够引出四者的关系.

2.1 MessageQueue

  在Looper中,维持一个Thread对象以及MessageQueue,通过Looper的构造函数我们可以知道:

   private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);//传入的参数代表这个Queue是否能够被退出
mThread = Thread.currentThread();
}

  Looper在构造函数里干了两件事情:

  • 将线程对象指向了创建Looper的线程
  • 创建了一个新的MessageQueue

  分析完构造函数之后,接下来我们主要分析两个方法:

  • looper.loop()
  • looper.prepare()

2.2 looper.loop()

  在当前线程启动一个Message loop机制,此段代码将直接分析出Looper、Handler、Message、MessageQueue的关系.

 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;//获得与Looper绑定的MessageQueue // 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(); //进入死循环,不断地去取对象,分发对象到Handler中消费
for (;;) {
Message msg = queue.next(); // 不断的取下一个Message对象,在这里可能会造成堵塞。
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);
} //在这里,开始分发Message了
//至于这个target是神马?什么时候被赋值的?
//我们一会分析Handler的时候就会讲到
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);
} //当分发完Message之后,当然要标记将该Message标记为 *正在使用* 啦
msg.recycleUnchecked();
}
}

  分析了上面的源代码,我们可以意识到,最重要的方法是:

  • queue.next()
  • msg.target.dispatchMessage(msg)
  • msg.recycleUnchecked()

  其实Looper中最重要的部分都是由MessageMessageQueue组成的有木有!这段最重要的代码中涉及到了四个对象,他们与彼此的关系如下:

  • MessageQueue:装食物的容器
  • Message:被装的食物
  • Handler(msg.target实际上就是Handler):食物的消费者
  • Looper:负责分发食物的人

2.3 looper.prepare()

  在当前线程关联一个Looper对象

  private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
//在当前线程绑定一个Looper
sThreadLocal.set(new Looper(quitAllowed));
}

  以上代码只做了两件事情: 1. 判断当前线程有木有Looper,如果有则抛出异常(在这里我们就可以知道,Android规定一个线程只能够拥有一个与自己关联的Looper)。 2. 如果没有的话,那么就设置一个新的Looper到当前线程。

3.Handler

  由于我们使用Handler的通常性的第一步是:

 Handler handler = new Handler(){
//你们有没有很好奇这个方法是在哪里被回调的?
//我也是!所以接下来会分析到哟!
@Override
public void handleMessage(Message msg) {
//Handler your Message
}
};

  所以我们先来分析Handler的构造方法

 //空参数的构造方法与之对应,这里只给出主要的代码,具体大家可以到源码中查看
public Handler(Callback callback, boolean async) {
//打印内存泄露提醒log
.... //获取与创建Handler线程绑定的Looper
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
//获取与Looper绑定的MessageQueue
//因为一个Looper就只有一个MessageQueue,也就是与当前线程绑定的MessageQueue
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async; }

4.问题

  • Looper.loop()死循环中的msg.target是什么时候被赋值的?
  • handler.handleMessage(msg)在什么时候被回调的?

4.1 Looper.loop()死循环中的msg.target是什么时候被赋值的?

  要分析这个问题,很自然的我们想到从发送消息开始,无论是handler.sendMessage(msg)还是handler.sendEmptyMessage(what),我们最终都可以追溯到以下方法

 public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
//引用Handler中的MessageQueue
//这个MessageQueue就是创建Looper时被创建的MessageQueue
MessageQueue queue = mQueue; if (queue == null) {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
return false;
}
//将新来的Message加入到MessageQueue中
return enqueueMessage(queue, msg, uptimeMillis);
}

  接下来分析enqueueMessage(queue, msg, uptimeMillis):

 private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
//显而易见,大写加粗的赋值啊!
**msg.target = this;**
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);

4.2 handler.handleMessage(msg)在什么时候被回调的?

  通过以上的分析,我们很明确的知道Message中的target是在什么时候被赋值的了,我们先来分析在Looper.loop()中出现过的过的dispatchMessage(msg)方法

 public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
//看到这个大写加粗的方法调用没!
**handleMessage(msg);**
}

  加上以上分析,我们将之前分析结果串起来,就可以知道了某些东西: Looper.loop()不断地获取MessageQueue中的Message,然后调用与Message绑定的Handler对象的dispatchMessage方法,最后,我们看到了handleMessage就在dispatchMessage方法里被调用的。

  通过以上的分析,我们可以很清晰的知道Handler、Looper、Message、MessageQueue这四者的关系以及如何合作的了。

5.总结

  当调用handler.sendMessage(msg)方法发送一个Message时,实际上这个Message是发送到与当前线程绑定的一个MessageQueue中,然后与当前线程绑定Looper将会不断的从MessageQueue中取出新的Message,调用msg.target.dispathMessage(msg)方法将消息分发到与Message绑定的handler.handleMessage()方法中。

一个Thread对应多个Handler 一个Thread对应一个LooperMessageQueueHandlerThread共享LooperMessageQueueMessage只是消息的载体,将会被发送到与线程绑定的唯一的MessageQueue中,并且被与线程绑定的唯一的Looper分发,被与其自身绑定的Handler消费。

Looper、MessageQueue、Message、Handler的关系的更多相关文章

  1. Android消息机制:Looper,MessageQueue,Message与handler

    Android消息机制好多人都讲过,但是自己去翻源码的时候才能明白. 今天试着讲一下,因为目标是讲清楚整体逻辑,所以不追究细节. Message是消息机制的核心,所以从Message讲起. 1.Mes ...

  2. 讲讲Handler+Looper+MessageQueue 关系

    Handler+Looper+MessageQueue这三者的关系其实就是Android的消息机制.这块内容相比开发人员都不陌生,在面试中,或者日常开发中都会碰到,今天就来讲这三者的关系. 概述: H ...

  3. Android 异步消息处理机制 让你在深入了解 Looper、Handler、Message之间的关系

    转载请注明出处:http://blog.csdn.net/lmj623565791/article/details/38377229 ,本文出自[张鸿洋的博客] 非常多人面试肯定都被问到过,请问And ...

  4. Android Handler处理机制 ( 三 ) ——Handler,Message,Looper,MessageQueue

    在android中提供了一种异步回调机制Handler,使用它,我们可以在完成一个很长时间的任务后做出相应的通知 handler基本使用: 在主线程中,使用handler很简单,new一个Handle ...

  5. Handler Looper MessageQueue 之间的关系

    Handler Looper MessageQueue 之间的关系 handler在安卓开发中常用于更新界面ui,以及其他在主线程中的操作.内部结构大概图为: 1.handler持有一个Looper对 ...

  6. Android Handler处理机制 ( 二 ) ——Handler,Message,Looper,MessageQueue

    Android是消息驱动的,实现消息驱动有几个要素: 消息的表示:Message 消息队列:MessageQueue 消息循环,用于循环取出消息进行处理:Looper 消息处理,消息循环从消息队列中取 ...

  7. Android Handler处理机制 ( 一 )(图+源码分析)——Handler,Message,Looper,MessageQueue

    android的消息处理机制(图+源码分析)——Looper,Handler,Message 作为一个大三的预备程序员,我学习android的一大乐趣是可以通过源码学习 google大牛们的设计思想. ...

  8. Looper Handler MessageQueue Message 探究

    Android消息处理的大致的原理如下: 1.有一个消息队列,可以往队列中添加消息 2.有一个消息循环,可以从消息队列中取出消息 Android系统中这些工作主要由Looper和Handler两个类来 ...

  9. Android Handler 机制 - Looper,Message,MessageQueue

    Android Studio 2.3 API 25 从源码角度分析Handler机制.有利于使用Handler和分析Handler的相关问题. Handler 简介 一个Handler允许发送和处理M ...

随机推荐

  1. linux 解压zip文件

    linux 解压zip文件 学习了:https://blog.csdn.net/hbcui1984/article/details/1583796 unzip xx.zip

  2. Android调试工具_ Stetho

    Stetho是Facebook开源的一个Android平台调试工具. Stetho能实如今不root手机的情况下,通过Chrome查看App的布局,Sqlite,SharedPreference.Ne ...

  3. 聚合类新闻client产品功能点详情分析

    产品功能点 功能 今日头条 百度新闻 鲜果 ZAKER 媒体订阅 × √ ★ ★ 个性化内容推荐 ★ √ × × 个性化订阅(RSS) × × ★ × 视频新闻 × × × × 评论盖楼 √ √ √ ...

  4. 使用VLC搭建视频直播服务器

    去年我们信息之夜我们进行过视频直播服务,当时我们使用了WMS(Windows Media Server)实现了这个服务,但是编码是微软的WMV,因而像iPhone/Android这样的智能手机无法观看 ...

  5. var和dynamic的应用 var、动态类型 dynamic 深入浅析C#中的var和dynamic ----demo

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  6. leetcode:238. Product of Array Except Self(Java)解答

    转载请注明出处:z_zhaojun的博客 原文地址 题目地址 Product of Array Except Self Given an array of n integers where n > ...

  7. 【iOS系列】-UIScrollView的介绍及结合UIPageControl实现图片播放的实例

    [iOS系列]-UIScrollView的介绍及结合UIPageControl实现图片播放的实例 第一:UIScrollView的常用属性 //表示UIScrollView内容的尺寸,滚动范围 @pr ...

  8. ASP.NET for WebApi

    WebApi,听说过吧?呵呵. 感觉比WebService,WCF要强.尤其是那个啥WCF,啥鬼东西,真难懂.真难搞.真难用. 说比WebService要强,是因为不用在本地先生成个代理.而且XML也 ...

  9. 2016/3/31 ①全选时 下面选项全选中 ② 下面不选中时 全选取消 ③在“” 中 转义字符的使用\ onclick=\"Checkpa(this,'flall')\"; ④区别于分别实现 重点在于两种情况合并实现

    testxuanbuxuan.php <!DOCTYPE html> <html lang="en"> <head> <meta char ...

  10. jvm部分知识总结

    1.jvm有三种执行模式,分别是解释执行,混合执行和编译执行,默认情况是混合执行模式. java version " Java(TM) SE Runtime Environment (bui ...