Handler的作用分析

Handler的构造函数:

public Handler() {
        this(null, false);
    }

接着,调到这个函数

    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中有一个属性mLooper,并且在构建Handler的时候,mLooper属性不能为null,否则就报错。报错的原因就是没有调用Looper.prepare()方法。
Looper类中:

    public static void prepare() {
        prepare(true);
    }

    private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
        //同一个线程,只能调用一次prepare,代表了一个线程只会和一个Looper对象,产生关联。
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed));
    }

sThreadLocal这个属性是与Thread想关联的,每个线程有一个,并且是独享的。prepare()的目的就是让某一个线程和一个Looper进行关联。但是和Looper关联的同时,也产生了一个MessageQueue。

    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

这样的话,一个Thread,一个Looper,一个MessageQueue就产生了对应的关联,并且是一对一的关系。然后Handler再与他们(Thread,Looper,MessageQueue)产生关系,由于可以new多个Handler,意味着就可以Handler和(Thread,Looper,MessageQueue)是N:1的关联关系。

Handler建立之后,主要作用投递消息和处理消息(这样做的目的是让消息有秩序的一个个进行处理)。

  1. post方法:
    public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }
    private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;
        return m;
    }

post方法,传递一个Runnable,然后Ruannable包装成Message的callback属性(用另外的方法进行处理)。然后也是以Message的方式进行事件投递。

  1. sendMessage方法:
    public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }

可以看到post和sendMessage都是调用sendMessageDelayed。

    public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
    //跟Looper对应的mQueue
        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);
    }

其实就是msg进入MessageQueue队列

    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    //设置消息的处理对象就是当前的handler,循环的时候还能看到这个target
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

消息msg进入了队列MessageQueue中,当然还要取消息msg。消息队列是一直不停的循环工作,将消息取出来,然后交给对应的入队的Handler进行处理。

    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);
            }
            //这个target就是刚才那个设置的target,用来处理消息的
            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();
        }
    }

消息取出来了,还是需要handler进行处理,通过dispatchMessage进行消息分发和处理。

    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
           //这个就是处理post(Runnable r),r无法携带消息信息
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            //这个处理普通的消息,msg可以携带信息
            handleMessage(msg);
        }
    }

平时我们复写的handleMessage,此刻就能够处理消息内容了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值