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

handler 源码分析

时间:2015-06-25 10:29:10      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:handler

handler 
Looper 轮询器
MessageQueue 消息对象

1 主线程在一创建的时候就会调用,    public static void prepareMainLooper() {}构造方法。
    public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }


2 在prepareMainLooper(){} 内部调用了 prepare(false);方法,这就是在子线程中new Handler()会抱错的关键

    prepare(quitAllowed) {}方法里面设置了一个Looper对象,如果已经有了 Looper 对象,会抛出异常 Only one Looper may be created per thread
    所以说一个 Handler只能有一个Looper对象
    private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed));//创建一个 Looper构造器
    }

3 在 Looper 的构造器中
    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);//创建了 MessageQueue对象
        mRun = true;
        mThread = Thread.currentThread();//线程对象
    }


4 但是在 handler(){}的源码构造方法中
    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;
    }

5 查看 Looper.myLooper();
    public static Looper myLooper() {
        return sThreadLocal.get();//返回的是一个 Looper对象,这里就跟 2的结果一样了
    }
所以在4 中抛出异常,跟2 也一样了
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can‘t create handler inside thread that has not called Looper.prepare()");
        }
所以敢肯定(1 2 3)的原理就是主线程 Handler的工作原理
而 (4 5)就是我们手动创建 Handler的时候的工作原理。


handler.sendMessage(msg);他做的是将消息入队操作
6 经过源码跟踪,会发现在调用enqueueMessage(){}构造方法的时候,所做的事情就是将消息就行,入栈处理
   private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);//注意这里,想必从字面意思理解,enqueueMessage就是入栈的意思吧
    }

7 看enqueueMessage()所做的事情
    final boolean enqueueMessage(Message msg, long when) {
        if (msg.isInUse()) {
            throw new AndroidRuntimeException(msg + " This message is already in use.");
        }
        if (msg.target == null) {
            throw new AndroidRuntimeException("Message must have a target.");
        }

        boolean needWake;
        synchronized (this) {
            if (mQuiting) {
                RuntimeException e = new RuntimeException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w("MessageQueue", e.getMessage(), e);
                return false;
            }

            msg.when = when;
            Message p = mMessages;
            if (p == null || when == 0 || when < p.when) {
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg; //将消息对象的引用赋值给 Message
                needWake = mBlocked;
            } else {
                // Inserted within the middle of the queue.  Usually we don‘t have to wake
                // up the event queue unless there is a barrier at the head of the queue
                // and the message is the earliest asynchronous message in the queue.
                needWake = mBlocked && p.target == null && msg.isAsynchronous();
                Message prev;
                for (;;) {
                    prev = p;
                    p = p.next;
                    if (p == null || when < p.when) {
                        break;
                    }
                    if (needWake && p.isAsynchronous()) {
                        needWake = false;
                    }
                }
                msg.next = p; // invariant: p == prev.next
                prev.next = msg; //将消息对象的引用赋值给 Message
            }
        }
        if (needWake) {
            nativeWake(mPtr);
        }
        return true;
    }
8 那么问题来了,消息引用都传递给Message对象了,那是如何从 Message中吧消息分发出去,并响应呢?这就得看 Looper的源码中的 public static void loop() {}方法
其实 loop就是一个轮询器,在不断的从  MessageQueue中获取消息,可以看 loop()中的 Message msg = queue.next(); 内部实现源码,next() 方法就是消息队列的出队方法。不过由于这个方法的代码稍微有点长,我就不贴出来了,它的简单逻辑就是如果当前MessageQueue中存在mMessages(即待处理消息),就将这个消息出队,然后让下一条消息成为mMessages,否则就进入一个阻塞状态,一直等到有新的消息入队
    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 (;;) {//天呐,在这里居然是 for的空循环
            //queue.next() 出现了,有兴趣的可以点进去看看
            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);
            }

            msg.target.dispatchMessage(msg);//我们又发现了什么?对,msg.target代表的是Handler,调用了dispatchMessage方法
            // 这样我相信大家就都明白了为什么handleMessage()方法中可以获取到之前发送的消息了吧!
            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.recycle();
        }
    }

handler 源码分析

标签:handler

原文地址:http://blog.csdn.net/lxcay9/article/details/46632879

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