Android Handler详解:消息发送详解,缓存池大小..

2018-01-15  本文已影响0人  Fighter_hance

关于Handler的一些构造函数的解释,请参考Handler主要构造参数,通过这篇文章,大致可以对Handler的构造有一个粗浅的认识

下面我们从源码的角度来仔细分析一下Hanlder的收发消息机制,以及主线程和子线程对Handler不同处理

在子线程中用handler收发消息的常见代码

        Thread uiThread = new Thread(uiRunable);
        uiThread.start();
    private Runnable uiRunable = new Runnable() {
        @Override
        public void run() {
            Looper.prepare();
            Handler uiHandler = new Handler(){
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    MiGuTvDebug.showDLevelLog("**GameMainActivity uiHandler msg**" + msg.what);
                }
            };
            Message msg = new Message();
            msg.what = 1;
            uiHandler.sendMessage(msg);
            Looper.loop();
        }
    };

我们先看第5行的代码,创建一个匿名内部类uiHandler ,我们具体看下他构造的过程

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

在这个方法里面,FIND_POTENTIAL_LEAKS的值为false,里面的逻辑我们暂时可以不用关注;紧接着我们通过Looper.myLooper()的方式获得一个Looper,当Looper为null的时候,抛出异常Can't create handler inside thread that has not called Looper.prepare(),因此在子线程中直接创建Hanlder会报错。

问题一:为什么我们调用了Looper.prepare()会使得mLooper 不为null,不报错?查看源码

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

其调用

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

static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

在这里我们可以知道当调用prepare的时候,我们会创建一个Looper到sThreadLocal里面,同时quitAllowed的值为true,请记住这是在子线程中调用Looper.prepare的时候,quitAllowed的值为true; Looper主要是与当前线程绑定,保证一个线程只会有一个Looper实例,同时一个Looper实例也只有一个MessageQueue

问题二: 这里的quitAllowed的值为true,或者为false有什么区别

quitAllowed的值有子线程和主线程的区别,子线程通过Looper.prepare来完成looper的创建,其中quitAllowed的值为true;然而主线程是通过Looper.prepareMainLooper来完成looper的创建,我们看下代码

    public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

从这里就可以发现,此处调用的prepare方法传入的值就为false

问题三:quitAllowed的值作用在
对于这个问题,我们先看下Looper.prepare中,new一个Looper的时候都做了什么

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

从这里我们可以看见Looper.prepare完成了消息队列的创建,同时将quitAllowed的值付给MessageQueue,MessageQueue的构造如下

    MessageQueue(boolean quitAllowed) {
        mQuitAllowed = quitAllowed;
        mPtr = nativeInit();
    }

在构造中有一个mQuitAllowed变量,我们知道当完成消息收发之后,我们需要调用Looper.quit或者quitSafely来退出这个Looper

//Looper.java
    public void quit() {
        mQueue.quit(false);
    }
//Looper.java
    public void quitSafely() {
        mQueue.quit(true);
    }

当调用quit或者quitSafely的时候,会调用MessageQueue的quit方法

//MessageQueue.java
    void quit(boolean safe) {
        if (!mQuitAllowed) {
            throw new IllegalStateException("Main thread not allowed to quit.");
        }

        synchronized (this) {
            if (mQuitting) {
                return;
            }
            mQuitting = true;

            if (safe) {
                removeAllFutureMessagesLocked();
            } else {
                removeAllMessagesLocked();
            }

            // We can assume mPtr != 0 because mQuitting was previously false.
            nativeWake(mPtr);
        }
    }

此时我们便可以知道quitAllowed的作用了,在线程中是允许调用quit或者quitSafely来完成退出Looper,因此子线程在prepare的时候new Looper(quitAllowed)的值为true,因此其是可以退出的;
但是主线程在prepareMainLooper的时候new Looper(quitAllowed)的值为false,因此主线程是不可以调用退出接口的,否则会报Main thread not allowed to quit.的错误

问题四:Looper.java中的quit和quitSafely区别
quit和quitSafely均会调用MessageQueue.java的quit方法,只不过传值不同罢了;当调用quit的时候,其间接调用的是removeAllMessagesLocked方法,而quitSafely其间接调用的是removeAllFutureMessagesLocked方法;

    private void removeAllMessagesLocked() {
        Message p = mMessages;
        while (p != null) {
            Message n = p.next;
            p.recycleUnchecked();
            p = n;
        }
        mMessages = null;
    }
    private void removeAllFutureMessagesLocked() {
        final long now = SystemClock.uptimeMillis();
        Message p = mMessages;
        if (p != null) {
            if (p.when > now) {
                removeAllMessagesLocked();
            } else {
                Message n;
                for (;;) {
                    n = p.next;
                    if (n == null) {
                        return;
                    }
                    if (n.when > now) {
                        break;
                    }
                    p = n;
                }
                p.next = null;
                do {
                    p = n;
                    n = p.next;
                    p.recycleUnchecked();
                } while (n != null);
            }
        }
    }

removeAllMessagesLocked方法的代码比较简单,通过一个循环,将所有的消息全部移除掉,包括延迟的消息;我们查看removeAllFutureMessagesLocked方法的第五行,通过对消息的创建时间和当前时间做对比,如果消息时间大于当前时间,即这个消息是延迟消息,则我们会移除掉;针对消息列队里面非延迟消息,则会通过第七行的else交给handler进行处理

现在Looper,消息队列都创建好了,现在就剩下消息的收发了;
我们来看uiHandler.sendMessage(msg);

//将消息插入到消息列队的尾端
    public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }
    public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        //SystemClock.uptimeMillis()获得是手机启动到当前的这段时间,其中是不包括系统深度休眠的时间,SystemClock.elapsedRealtime()和SystemClock.elapsedRealtimeNanos()表示系统开机到当前的时间总数。它包括了系统深度睡眠的时间。
        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;
        }
        //enqueue(排队)
        return enqueueMessage(queue, msg, uptimeMillis);
    }

最终会调用MessageQueue.java的enqueueMessage方法

    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就是指我们的Handler,当其为null的时候,抛出异常Message must have a target
当消息在被使用的时候,抛出异常This message is already in use
当我们调用了Looper的quit或者quitSafely方法之后,会调用MessageQueue.java的quit方法,在这个方法里面会将mQuitting设置为true,因此当发送消息的时候,如果发现已经调用了相关退出方法,则会抛出异常sending message to a Handler on a dead thread
第20行,每一个MessageQueue使用的是mMessages来保持一个消息
从22到52行,按照时间顺序将消息进行入队操作

问题五:既然MessageQueue使用变量mMessages来维持一个队列,那一个变量怎么对应那么多的
消息队列?,我们先看下Message.java这个类

public final class Message implements Parcelable {

    // sometimes we store linked lists of these things
    /*package*/ Message next;
    
    private static final Object sPoolSync = new Object();
    private static Message sPool;
    private static int sPoolSize = 0;

    private static final int MAX_POOL_SIZE = 50;
}

Message类是一个序列化的类,因此可以在进程间进行传递消息;Message的成员有next、sPool和sPoolSize,可以看出这是一个典型的链表结构,sPool就是一个全局的消息池即链表,next记录链表中的下一个元素,sPoolSize记录链表长度,MAX_POOL_SIZE表示链表的最大长度为50。
因此通过next和sPool我们便可以获取下一个消息;

问题六:那缓存很多的消息,会造成内存泄漏吗?
答案是不会的,至于为什么,我们需要结合Looper.loop方法来看;

问题七:消息队列最大缓存大小是50,那是不是说如果缓存了超过50个的消息,则在不处理的情况下,无法塞入第51个消息?
答案是否,在我们调用sendmessage的时候,其实是向message这个链表的尾端插入一个message,这个长度是没有限制的,所以如果你不断通过new message的方式去调用sendmessage的时候,是会出现内存溢出的问题的;然而如果你通过Message.obtain方法去获取一个消息,其是在消息池中获得一个消息,当然当消息池没有消息的时候,会new一个消息;
MAX_POOL_SIZE主要用在缓存的消息池中,这个消息池最大缓存50个消息,即当调用obtain方法之后,消息池中缓存的消息数减一,当调用loop方法之后,消息池中的消息数加一,当消息池中的消息数大于MAX_POOL_SIZE的时候,则消息池中的消息数不加一,也不将消息添加到消息池中,而这个消息池主要用来重复利用从而避免更多的内存消耗。

我们来看下Meesage.obtain()这个方法

    /**
     * Return a new Message instance from the global pool. Allows us to
     * avoid allocating new objects in many cases.
     * 从全局的消息池返回一个消息实例,这么避免创建很多实例
     */
    public static Message obtain() {
        synchronized (sPoolSync) {
            if (sPool != null) {
                Message m = sPool;
                sPool = m.next;
                m.next = null;
                m.flags = 0; // clear in-use flag
                sPoolSize--;
                return m;
            }
        }
        return new Message();
    }

在第一次调用obtain方法的时候,sPool为null,因此会创建一个message放到Message的链表微端,此时消息池不做减一的操作
第7行即Message链表有数据的时候,通过sPool返回链表头中的一个消息,
第8行将sPool指向链表中的下一个数据,方便下次调用obtain的时候去除第二个数据
第12行,将消息缓存池的大小减一

我们在看下消息的发送部分Looper.java的loop方法

   /**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the loop.
     * 在当前线程中不断从MessageQueue中去取消息,交给消息的target属性的dispatchMessage去处理
     */
    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
            final Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            try {
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }

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

第18行,当调用loop方法之后,这个方法就进行循环,不断的获取消息,交给handler进行处理
第37行,msg.target即为handler,当调用dispatchMessage方法之后,即将消息交给Handler的handleMessage或者handleCallback进行处理,这里的handlerCallback即

    private static void handleCallback(Message message) {
        message.callback.run();
    }

可见当我们使用Handler的post(Runnable r)方法之后,这个Runnable的run方法就会被执行
因此post(Runnable r)并不是开启一个线程,只不过是单纯的方法调用罢了;

第59行调用了Message.java的recycleUnchecked

    /**
     * Recycles a Message that may be in-use.
     * Used internally by the MessageQueue and Looper when disposing of queued Messages.
     * 清空消息的一些状态量,这样是为了避免内存泄漏,然后将消息放入到消息池中,供循环使用
     */
    void recycleUnchecked() {
        // Mark the message as in use while it remains in the recycled object pool.
        // Clear out all other details.
        flags = FLAG_IN_USE;
        what = 0;
        arg1 = 0;
        arg2 = 0;
        obj = null;
        replyTo = null;
        sendingUid = -1;
        when = 0;
        target = null;
        callback = null;
        data = null;

        synchronized (sPoolSync) {
            if (sPoolSize < MAX_POOL_SIZE) {
                next = sPool;
                sPool = this;
                sPoolSize++;
            }
        }
    }

第9行到第19行,清空消息的一些状态,节约内存
第23行,将sPool指向下一个消息
第24行,sPool即Message
第25行,将缓存消息池大小加1

至于其他更新UI的方法,如
1: Handler的post(Runnable r)方法

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

其主要就是将Runnable复制给m.callback,当调用Looper的loop接口的时候,会间接的调用Runnable的run方法,

  1. View的post()方法
    /**
     * <p>Causes the Runnable to be added to the message queue.
     * The runnable will be run on the user interface thread.</p>
     *
     * @param action The Runnable that will be executed.
     *
     * @return Returns true if the Runnable was successfully placed in to the
     *         message queue.  Returns false on failure, usually because the
     *         looper processing the message queue is exiting.
     *
     * @see #postDelayed
     * @see #removeCallbacks
     */
    public boolean post(Runnable action) {
        final AttachInfo attachInfo = mAttachInfo;
        if (attachInfo != null) {
            return attachInfo.mHandler.post(action);
        }

        // Postpone the runnable until we know on which thread it needs to run.
        // Assume that the runnable will be successfully placed after attach.
        getRunQueue().post(action);
        return true;
    }

第15行,获得attachInfo
第17行,获得attachInfo的handler,并调用其post方法,完成UI更新,所以也就是调用Hanlder.post完成更新

这个方法会将Runnable添加到消息列队的尾端,同时runnable会运行在用户自己的线程中

  1. Activity的runOnUiThread()方法
    /**
     * Runs the specified action on the UI thread. If the current thread is the UI
     * thread, then the action is executed immediately. If the current thread is
     * not the UI thread, the action is posted to the event queue of the UI thread.
     *
     * @param action the action to run on the UI thread
     */
    public final void runOnUiThread(Runnable action) {
        if (Thread.currentThread() != mUiThread) {
            mHandler.post(action);
        } else {
            action.run();
        }
    }

也很容易理解了

上一篇下一篇

猜你喜欢

热点阅读