Android的消息机制

在更新UI的操作中,我们经常使用Handler发送数据来更新UI,那么这个过程是怎么样的,现在来分析一下:


总体过程:
首先主线程里建立消息循环,消息循环在looper()对象中,有消息队列,然后,我们是通过handler与looper()对象建立起关联起来,从而与消息队列建立起关联,通过在子线程调用sendmessage()和post()的方法将message发送到消息队列,在消息队列中,message又会调用handler的dispatchMessage()的方法处理相应操作。

首先UI线程的消息循环是在ActivityThread.main创建的,

//初始化Looper
Looper.prepareMainLooper();
    //创建ActivityThread对象,并绑定到AMS
   ActivityThread thread = new ActivityThread();
   //一般的应用程序都不是系统应用,因此设置为false,在这里面会绑定到AMS
    thread.attach(false);

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

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

    // End of event ActivityThreadMain.
    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
    //开启循环
    Looper.loop();

    throw new RuntimeException("Main thread loop unexpectedly exited");

这里就在主线程创建了looper对象,并且与主线程绑定起来,执行循环。
再来看hanler类

public Handler()
{
    mLooper=Looper.myLooper();//获取Looper
    if(mLooper==null)
    {
        throw new RuntimeException(
        "Can not create handler inside thread that has not called Looper.prepare()")

    }
    mQueue=mlooper.mQueue;//获取消息队列
    mcallback=null;
}

在handler的构造方法中,我们获取到了looper对象,从而就与消息队列关联了起来。
然后再看我们常用的方法sendEmptyMessageXXX、postXXX方法与sendMessageXXX方法之间的关系,我们可以看到在Handler中所有可以直接或间接向消息队列发送Message的方法最终都调用了sendMessageAtTime方法

public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
        MessageQueue queue = mQueue;
        if (queue == null) {
            RuntimeException e = new RuntimeException(
                    this + " sendMessageAtTime() called with no mQueue");
            Log.w("Looper", e.getMessage(), e);
            return false;
        }
        //注意下面这行代码
        return enqueueMessage(queue, msg, uptimeMillis);

再看enqueueMessage()

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        //注意下面这行代码
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        //注意下面这行代码
        return queue.enqueueMessage(msg, uptimeMillis);
}

这里看到msg.target就是我们的handler,可以看到将handler封装进了message对象里面,那么最后在消息队列的循环中,我们就通过msg.target.dispatchMessage()调用了原hanndler的处理方法,也是是我们常写的handlermessage(Message m)和post(Runnable r)了。这样就达到了我们的目的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值