码迷,mamicode.com
首页 > 其他好文 > 详细

Handler工作原理

时间:2018-10-14 23:34:10      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:emc   循环   called   further   als   消息机制   contain   lock   lis   

Handler是消息机制的面板类,我们通过Handler.send或者post消息然后在handleMessage()中去处理消息.

发送消息

    public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }

    public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }

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

    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }
sendMessage操作都只是对Message做了一个入队的操作.Looper无限循环从MessageQueue中取出Message然后调用Handler的dispatchMessage来处理消息

处理消息

    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }
msg的callback是一个Runnable,handlecallback(msg)就是调用了Runnable的run方法.

callable接口

第五行的mCallback是一个接口,定义如下
    /**
     * Callback interface you can use when instantiating a Handler to avoid
     * having to implement your own subclass of Handler.
     */
    public interface Callback {
        /**
         * @param msg A {@link android.os.Message Message} object
         * @return True if no further handling is desired
         */
        public boolean handleMessage(Message msg);
    }
可以通过Handler handler = new Handler(new CallBack(){})来使用,作用就是避免创建Handler的子类.
 

Handler工作原理

标签:emc   循环   called   further   als   消息机制   contain   lock   lis   

原文地址:https://www.cnblogs.com/coconna/p/9788701.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!