源码学习之Handler

最近有些心烦,浮躁,烦到不行,最后给自己灌了点鸡汤,哈哈哈哈哈。人要有管理自己情绪的能力,要有自省能力,要努力!!!以后要多看看源码,不只是说说而已!!
Handler、Looper、MessageQueue三者之间的关系,几乎每次面试都必问啊,现在就来看看看看源码,更深刻的了解一下吧。

木有对象,先new一个出来啊。
Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };
public Handler() {
        this(null, false);
    }

public Handler(Looper looper) {
        this(looper, null, false);
这两种是比较常用的方法。第二种主要用在子线程更新UI,需要传递一个getMainLooper()。

如果不传递looper,那么handler是怎么和looper进行关联呢,是的,需要调用Looper.prepare()方法。在UI线程使用handler的时候,开发人员并没有调用这个方法,是因为在ActivityThread的main方法里已经调用过了,有图有真相。
这里写图片描述
下面来看一下Looper.prepare()方法里都做了什么。

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

先从sThreadLocal里取,如果已经有值,就会抛异常,所以这个方法,只能调用一次,这也说明了每个线程的handler只能对应一个looper。如果没有的话,会new一个Looper,和sThreadLocal进行关联,同时MessageQueue也进行了初始化。

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

这样,Handler和Looper、MessageQueue就关联起来了。

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的主要作用有两个,1:处理Message和Runnable类型的信息;2:和子线程通信,更新UI。
当发送一条消息之后,会调用handler的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);
    }

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);

最终会调用MessageQueue的enqueueMessage(Message msg, long when)方法。
boolean enqueueMessage(Message msg, long when) {
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }
        if (msg.isInUse()) {
            throw new IllegalStateException(msg + " This message is already in use.");
        }

        synchronized (this) {
            if (mQuitting) {
                IllegalStateException e = new IllegalStateException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w(TAG, e.getMessage(), e);
                msg.recycle();
                return false;
            }

            msg.markInUse();
            msg.when = when;
            Message p = mMessages;
            boolean needWake;
            if (p == null || when == 0 || when < p.when) {
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg;
                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;
            }

            // We can assume mPtr != 0 because mQuitting is false.
            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }

首先会判断msg.target 是否为空,target就是负责处理这个消息的Handler,默认为发送消息的hanlder,如果为空的话,message就不会被处理,也就没有意义了。看源码可知,message是通过链表的方式被存储起来的。
接下来看看消息是如何被hanlder处理的吧,这时候就轮到Looper闪亮登场了。调用Looper.loop()以后,会循环从MessageQueue里边取出消息,交给对应的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 (;;) {
            /**
            MessageQueue的next()方法会一直循环,知道取出消息,所以在这会一直阻塞,
            /***
            Message msg = queue.next(); // might block 从messagequeue里取出一条消息

            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);//交给handler处理

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

public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

如果message设置了callback,就会回调callback的run方法,如果handler设置了callback,会调用callback的handleMessage方法,否则会调用handler的handleMessage方法。

Handler是匿名内部类,会持有外部类的引用,所以在使用的时候要注意内存泄露的问题。如果是在Activity内使用,可以在onDestroy的时候,remove消息,还看过有些方法是把Activity保存成弱引用的方式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值