Android Handler消息机制实现原理

2020-06-13  本文已影响0人  林锦洲

https://www.jianshu.com/p/6cc4d4b4676b

Looper,MessageQueue,Message,ThreadLocal,Handler

1.首先Looper.prepare()创建Looper并初始化Looper持有的消息队列MessageQueue,创建好后将Looper保存到ThreadLocal中方便Handler直接获取。
2.然后Looper.loop()开启循环,从MessageQueue里面取消息并调用handler的 dispatchMessage(msg) 方法处理消息。如果MessageQueue里没有消息,循环就会阻塞进入休眠状态,等有消息的时候被唤醒处理消息。
3.再然后我们new Handler()的时候,Handler构造方法中获取Looper并且拿到Looper的MessageQueue对象。然后Handler内部就可以直接往MessageQueue里面插入消息了,插入消息即发送消息,这时候有消息了就会唤醒Looper循环去处理消息。处理消息就是调用dispatchMessage(msg) 方法,最终调用到我们重写的Handler的handleMessage()方法。

作者:developerzjy
链接:https://www.jianshu.com/p/6cc4d4b4676b
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

https://blog.csdn.net/qian520ao/article/details/78262289#2-主线程的消息循环机制是什么

https://blog.csdn.net/u012759878/article/details/52004547

https://blog.csdn.net/lmj623565791/article/details/38377229

上一篇下一篇

猜你喜欢

热点阅读