Android Handler 原理分析

Handler一个让无数android开发者头疼的东西,希望我今天这边文章能为您彻底根治这个问题

今天就为大家详细剖析下Handler的原理

Handler使用的原因

1.多线程更新Ui会导致UI界面错乱

2.如果加锁会导致性能下降

3.只在主线程去更新UI,轮询处理

Handler使用简介

其实关键方法就2个一个sendMessage,用来接收消息

另一个是handleMessage,用来处理接收到的消息

下面是我参考疯狂android讲义,写的一个子线程和主线程之间相互通信的demo

对原demo做了一定修改

public class MainActivity extends AppCompatActivity {

public final static String UPPER_NUM="upper_num";

private EditText editText;

public jisuanThread jisuan;

public Handler mainhandler;

private TextView textView;

class jisuanThread extends Thread{

public Handler mhandler;

@Override

public void run() {

Looper.prepare();

final ArrayList al=new ArrayList<>();

mhandler=new Handler(){

@Override

public void handleMessage(Message msg) {

if(msg.what==0x123){

Bundle bundle=msg.getData();

int up=bundle.getInt(UPPER_NUM);

outer:

for(int i=3;i<=up;i++){

for(int j=2;j<=Math.sqrt(i);j++){

if(i%j==0){

continue outer;

}

}

al.add(i);

}

Message message=new Message();

message.what=0x124;

Bundle bundle1=new Bundle();

bundle1.putIntegerArrayList("Result",al);

message.setData(bundle1);

mainhandler.sendMessage(message);

}

}

};

Looper.loop();

}

}

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

editText= (EditText) findViewById(R.id.et_num);

textView= (TextView) findViewById(R.id.tv_show);

jisuan=new jisuanThread();

jisuan.start();

mainhandler=new Handler(){

@Override

public void handleMessage(Message msg) {

if(msg.what==0x124){

Bundle bundle=new Bundle();

bundle=msg.getData();

ArrayList al=bundle.getIntegerArrayList("Result");

textView.setText(al.toString());

}

}

};

findViewById(R.id.bt_jisuan).setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

Message message=new Message();

message.what=0x123;

Bundle bundle=new Bundle();

bundle.putInt(UPPER_NUM, Integer.parseInt(editText.getText().toString()));

message.setData(bundle);

jisuan.mhandler.sendMessage(message);

}

});

}

}

Hanler和Looper,MessageQueue原理分析

1.Handler发送消息处理消息(一般都是将消息发送给自己),因为hanler在不同线程是可使用的

2.Looper管理MessageQueue

Looper.loop死循环,不断从MessageQueue取消息,如果有消息就处理消息,没有消息就阻塞

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();

}

}

这个是Looper.loop的源码,实质就是一个死循环,不断读取自己的MessQueue的消息

3.MessQueue一个消息队列,Handler发送的消息会添加到与自己内联的Looper的MessQueue中,受Looper管理

private Looper(boolean quitAllowed) {

mQueue = new MessageQueue(quitAllowed);

mThread = Thread.currentThread();

}

这个是Looper构造器,其中做了2个工作,

1.生成与自己关联的Message

2.绑定到当前线程

主线程在初始化的时候已经生成Looper,

其他线程如果想使用handler需要通过Looper.prepare()生成一个自己线程绑定的looper

这就是Looper.prepare()源码,其实质也是使用构造器生成一个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));

}

4.handler发送消息会将消息保存在自己相关联的Looper的MessageQueue中,那它是如何找到这个MessageQueue的呢

public Handler(Callback callback, boolean async) {

if (FIND_POTENTIAL_LEAKS) {

final Class extends Handler> klass = getClass();

if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&

(klass.getModifiers() & Modifier.STATIC) == 0) {

Log.w(TAG, "The following Handler class should be static or leaks might occur: " +

klass.getCanonicalName());

}

}

mLooper = Looper.myLooper();

if (mLooper == null) {

throw new RuntimeException(

"Can't create handler inside thread that has not called Looper.prepare()");

}

mQueue = mLooper.mQueue;

mCallback = callback;

mAsynchronous = async;

}

这个是Handler的构造方法,它会找到一个自己关联的一个Looper

public static Looper myLooper() {

return sThreadLocal.get();

}

没错,他们之间也是通过线程关联的,得到Looper之后自然就可以获得它的MessageQueue了

5.我们再看下handler如发送消息,又是如何在发送完消息后,回调HandlerMessage的

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {

msg.target = this;

if (mAsynchronous) {

msg.setAsynchronous(true);

}

return queue.enqueueMessage(msg, uptimeMillis);

}

这个就是Handler发送消息的最终源码,可见就是将一个message添加到MessageQueue中,那为什么发送完消息又能及时回调handleMessage方法呢

大家请看上边那个loop方法,其中的for循环里面有一句话msg.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);

}

}

这就是这句话,看到了吧里面会调用hanlerMessage,一切都联系起来了吧

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

android 实例源码解释,Android Handler 原理分析及实例代码相关推荐

  1. 老李推荐:第6章1节《MonkeyRunner源码剖析》Monkey原理分析-事件源-事件源概览 1...

    老李推荐:第6章1节<MonkeyRunner源码剖析>Monkey原理分析-事件源-事件源概览 在上一章中我们有简要的介绍了事件源是怎么一回事,但是并没有进行详细的描述.那么往下的这几个 ...

  2. 老李推荐:第5章5节《MonkeyRunner源码剖析》Monkey原理分析-启动运行: 获取系统服务引用 1...

    老李推荐:第5章5节<MonkeyRunner源码剖析>Monkey原理分析-启动运行: 获取系统服务引用 上一节我们描述了monkey的命令处理入口函数run是如何调用optionPro ...

  3. 老李推荐:第6章6节《MonkeyRunner源码剖析》Monkey原理分析-事件源-事件源概览-命令队列...

    老李推荐:第6章6节<MonkeyRunner源码剖析>Monkey原理分析-事件源-事件源概览-命令队列 事件源在获得字串命令并把它翻译成对应的MonkeyEvent事件后,会把这些事件 ...

  4. ubuntu-18.04.4 Android系统源码TP1A(Android 13)下载及编译

    继上一篇博客介绍了VMware Workstation15 配置ubuntu-18.04.4,这篇主要介绍安装后环境搭建,Android源码的下载与编译.小编当前下载的是当前最新的代码,是主干分支代码 ...

  5. 顺序线性表 ---- ArrayList 源码解析及实现原理分析

    原创播客,如需转载请注明出处.原文地址:http://www.cnblogs.com/crawl/p/7738888.html ------------------------------------ ...

  6. android 日历源码解析,Android 4.0日历(calendar)源码分析之概览

    Calendar 从4.0开始,谷歌android系统有了脱碳换骨的改变,相应的日历应用的代码架构也跟2.*完全不同.代码更规范,当然也更复杂,且涉及到了android开发的方方面面. 如果你熟悉了i ...

  7. Android系统源码导入Android studio

    1,下载Android源码 网上很多文章,多半都是在清华或者某个大学的镜像地址下载,repo init...巴拉巴拉的,这里repo就是git的封装,怎么下载怎么运行,不多说了,百度一下.下载哪个版本 ...

  8. spring源码阅读--aop实现原理分析

    aop实现原理简介 首先我们都知道aop的基本原理就是动态代理思想,在设计模式之代理模式中有介绍过这两种动态代理的使用与基本原理,再次不再叙述. 这里分析的是,在spring中是如何基于动态代理的思想 ...

  9. android sensor源码,阅读android有关sensor的源码总结 - JerryMo06的专栏 - CSDN博客

    虽然这篇文章写得很差,因为赶时间,所以就匆匆忙忙地写出来自己作一个笔记.但是我想对大家应该有一点帮助. 1.有关sensor在Java应用程序的编程(以注册多个传感器为例,这程序是我临时弄出来的,可能 ...

最新文章

  1. Python 之 matplotlib (十六)Animation动画
  2. python中的break+while break+for
  3. java命令_JAVA与模式之命令模式
  4. SEO优化---学会建立高转化率的网站关键词库
  5. c语言中二维数组的结构体,怎么才能把结构体里面的二维数组打印出来?
  6. Java环境配置(linux安装jdk8)
  7. 卷积神经网络-进化史 | 从LeNet到AlexNet
  8. Python 科学计算库 Numpy 准备放弃 Python 2 了
  9. 2021年中国电热饭盒市场趋势报告、技术动态创新及2027年市场预测
  10. panoramic image view 全景照片查看器
  11. 苹果手机来电归属地_Python批量查询手机号码归属地
  12. 2370. 最长理想子序列(每日一难phase2--day6)
  13. ZT:【搞笑】某大学生毕业自我鉴定
  14. Git实用技巧36招
  15. 粘胶活化剂市场现状及未来发展趋势
  16. waf全称是什么?是干什么的?
  17. 对标测评YD云电脑和天翼云电脑公众版
  18. 计算机设置任务栏的大小要先,教你win7系统电脑调整任务栏预览窗口大小的方法...
  19. inline内联函数 static静态函数 普通函数区别
  20. WireShark找不到360wifi如何解决

热门文章

  1. C语言 数组排序 – 选择法排序 - C语言零基础入门教程
  2. java设计模式-简单工厂模式
  3. BugkuCTF-Reverse题SafeBox(NJCTF)
  4. c语言中词法分析怎么识别注释,C语言中的词法分析-如何在检测多行注释时使星号被读取并输出?...
  5. 提权命令_利用Linux文本操作命令ed进行提权
  6. strlen函数strcpy函数strcat函数的实现
  7. c语言编程算法精选,c语言经典程序算法【DOC精选】.doc
  8. et200sp模块接线手册_西门子PN/PN耦合器学习应用系列(1)-外观及接线
  9. python编程第八讲答案_小甲鱼Python第八讲课后习题
  10. linux下使用odbc连接mysql_Linux环境下通过ODBC访问MSSql Server