Android消息机制源码简析

简介

Android应用程序通过消息驱动,在线程间的通信中,通过Handler、Looper、MessageQueue来实现消息的传递和处理。

在使用时,一般我们会用Handler handler = new Handler();当前线程(一般是UI线程)创建一个Handler对象;
然后,通过在其他线程里使用handler.sendMessage(message) 来发送消息给当前线程
通过当前线程的handler里面的handleMessage 来处理来自其他线程的消息

以上是最简单的消息机制的运用,然而,其中到底发生了什么呢?接下来我们简单解析下源码到底做了什么

Handler、Looper、MessageQueue的创建过程

1、创建Handler,持有Looper和MessageQueue的实例

 public Handler(Callback callback, boolean async) {
        /*****/
        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;
    }

在使用new Handler()时,会先拿到当前线程的Looper对象,如果拿不到会报异常导致handler创建失败。
一般我们在UI线程中,是不需要手动去创建Looper对象的,因为系统会在Activity创建的时候,通过ActivityThread的main方法里,调用Looper.prepareMainLooper(); 来创建与UI线程绑定的Looper

public static void main(String[] args) {
        //省略
        //通过prepareMainLooper创建Looper,并绑定到当前UI线程
        Looper.prepareMainLooper();

        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值