Android的消息机制

来源:互联网 发布:c 程序员用mac好吗 编辑:程序博客网 时间:2024/06/05 02:41

碰巧昨天又一次看了苹果广告Think different,震撼之余还有感动。广告词如下:

Here’s to the crazy ones.

The misfits.The rebels.the troublemakers.

The round pegs in the square holes.

The ones who see things differently.

They’re not fond of rules. And they have no respect for status quo.

You can quote them,disagree with them,glorify or vilify them.

About the only thing you can’t do is ignore them.

Because they change things.They push human race forward.

And while some may see them as the crazy ones, we see genius.

Because the people who’re crazy enough to think they can change the world are the ones who do.


Android开发艺术探索第十章 阅读有感

Android的消息机制就是Handler的运行机制
主要包括Handler,MessageQueue和Looper,ThreadLocal。

理解ThreadLocal

概述

ThreadLocal是一个线程内部的数据存储类,通过它可以在指定的线程中存和取数据,是作用域为线程范围的容器。在不同线程中访问同一个ThreadLocal对象,获取到的值是不同的。

ThreadLocal的使用场景:

  • 当某些数据是以线程为作用域并且不同线程具有不同的数据副本的时候。
  • 复杂逻辑下的对象传递。比如当一个线程内,函数调用栈比较深,代码有多个入口,监听器需要贯穿整个执行过程时。

还有一种解决方案:提供一个全局的哈希表来存储数据和对象,需要创建一个Manager的类。

MessageQueue的理解

该类包含两个操作:

  • enqueueMessage(),往消息队列中插入一条消息
  • next(),从消息队列中取出一条消息并将其从消息队列中移除,如果消息列表中没有消息,那么next方法会一直阻塞在这里。

消息列表是单链表的数据结构

Looper的理解

概述

扮演消息循环角色,不停地从MessageQueue中查看是否有新消息,如果有新消息就会立刻处理,否则就一直阻塞在那里。

涉及到高频使用的方法

通过Looper.prepare()为当前线程创建一个Looper。prepareMainLooper()给主线程ActivityThread创建Looper

通过Looper.loop()开启消息循环

getMainLooper(),在任何地方获取到主线程的Looper

提供如下两个方法实现退出Looper/终止消息循环:

  • quit(),立刻退出
  • quitSafely(),通过设定的标示,当消息列表中的已有消息处理完毕后才安全退出。此时,Handler发送的消息将会失败

Handler的理解

概述

负责消息的发送和接收

发送消息的过程仅仅是想消息队列插入一条消息,MessageQueue的next()方法就会返回这条消息给Looper,Looper收到消息转交给Handler处理。

Handler处理分为如下两种情况:

  1. Message的Callback不为null,将先调用message的handleCallback,再调用Handler的handleMessage()来处理消息
  2. Message的Callback为null,如果Handle里的mCallback不为空,则执行该方法;如果Handler里的mCallback为空,则执行handleMessage()来处理消息。

由上述分析,可知:Handler里的mCallback回调优先级最高

补充

在初始化Activity时,主线程里的main()会通过调用Looper.preMainLooper()创建Looper,Looper.loop()启动消息循环。因此,在主线程创建Handler就不必像子线程那样执行上述两个方法。

小结

自从有了RxJava,安卓的线程切换变得异常方便。很自然,推测RxJava内部线程的切换仍然使用的是Handler那一套消息机制

P.S. 欢迎访问我的简书博客

0 0
原创粉丝点击