美文网首页
Handler + Looper + MessageQueue详

Handler + Looper + MessageQueue详

作者: kjy_112233 | 来源:发表于2017-08-09 16:15 被阅读0次

    一、使用详解

    (1)Handler使用

    //创建一个带有Looper的线程
    class LooperThread extends Thread{
        @Override
        public void run() {
            Looper.prepare();
            Looper.loop();
        }
    }
    
    //在主线程中创建,自动绑定主线程Looper
    private Handler uiHandler = new Handler() {
        //重写Handler的处理消息的方法handleMessage()
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    break;
            }
        }
    };
    //获取子线程实例
    LooperThread looperThread = new LooperThread();
    //开启子线程
    looperThread.start();
    //获取子线程Looper
    Looper loop = looperThread .getLooper();
    //手动绑定子线程Looper
    private Handler mHandler = new Handler(loop) {
        //重写Handler的处理消息的方法handleMessage()
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    break;
            }
        }
    };
    //发送消息
    Message message = new Message();
    message.what = 1;
    message.obj = "result";
    uiHandler.sendMessage(message )
    mHandler.sendMessage(message )
    

    (2)Handler构造方法

    • Handler():构造函数将通过调用Looper.myLooper()获取当前线程绑定的Looper对象,将该Looper对象保存到名为mLooper的成员字段中。
    • Handler(Looper looper):直接将该Looper保存到名为mLooper的成员字段中。
    • Handler(Callback callback):构造函数传递了Callback对象,Callback是Handler中的内部接口,需要实现其内部的handleMessage方法。
    • Handler(Looper looper, Callback callback)
      处理Message消息,通过实现Handler.Callback的handleMessage方法或重写Handler本身的handleMessage方法

    多线程实现:向Thread的post函数传入一个Runnable对象者重写Thread本身的run方法。

    二、源码解析

    (1)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());
                }
            }
            //获取当前线程的Looper对象
            mLooper = Looper.myLooper();
            if (mLooper == null) {
                throw new RuntimeException(
                    "Can't create handler inside thread " + Thread.currentThread()
                            + " that has not called Looper.prepare()");
            }
            //获取当前Looper的消息队列MessageQueue对象
            mQueue = mLooper.mQueue;
            mCallback = callback;
            mAsynchronous = async;
        }
    

    Handler.sendMessage发送消息

        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) {
            //Handler所绑定的消息队列MessageQueue
            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) {
            //将Message的target绑定为当前的Handler
            msg.target = this;
            if (mAsynchronous) {
                msg.setAsynchronous(true);
            }
            //通过queue.enqueueMessage(msg, uptimeMillis)我们将Message放入到消息队列中。
            return queue.enqueueMessage(msg, uptimeMillis);
        }
    

    Handler.dispatchMessage发送消息到Handler

        //派发消息到对应的Handler实例。根据传入的msg作出对应的操作
        public void dispatchMessage(Message msg) {
            if (msg.callback != null) {
                //使用了post发送消息,则执行handleCallback方法,回调Runnable复写的run方法
                handleCallback(msg);
            } else {
                //使用了sendMessage发送消息,则执行handleMessage,回调复写的handleMessage
                if (mCallback != null) {
                    if (mCallback.handleMessage(msg)) {
                        return;
                    }
                }
                handleMessage(msg);
            }
        }
    

    (2)Looper创建源码
    Looper.prepare()创建Looper,当前线程和Looper就进行了双向的绑定

        //Looper对象中通过sThreadLocal就可以找到其绑定的线程
        static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
    
        public static void prepare() {
            prepare(true);
        }
    
        private static void prepare(boolean quitAllowed) {
            //1个线程中只能对应1个Looper实例
            if (sThreadLocal.get() != null) {
                throw new RuntimeException("Only one Looper may be created per thread");
            }
            //创建Looper对象存放在ThreadLocal变量中
            sThreadLocal.set(new Looper(quitAllowed));
        }
        
        private Looper(boolean quitAllowed) {
            //创建消息队列对象
            mQueue = new MessageQueue(quitAllowed);
            mThread = Thread.currentThread();
        }
    

    Looper.loop()循环获取MessageQueue中消息Message

        public static void loop() {
            //获取当前线程所绑定的Looper
            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;
    
            //code...
    
            //消息循环
            for (;;) {
                //从消息队列中取出消息
                Message msg = queue.next(); // might block
                //若取出的消息为空,则线程阻塞
                if (msg == null) {
                    // No message indicates that the message queue is quitting.
                    return;
                }
                //code...
                try {
                    //Message所关联的Handler通过dispatchMessage方法让Handler处理该Message
                    msg.target.dispatchMessage(msg);
                    dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
                } finally {
                    if (traceTag != 0) {
                        Trace.traceEnd(traceTag);
                    }
                }
                //code...
                //释放消息占据的资源
                msg.recycleUnchecked();
            }
        }
    

    Looper类还提供了一些有用的方法

        //获取当前线程的Looper
        public static @Nullable Looper myLooper() {
            return sThreadLocal.get();
        }
        //获取looper对象所属线程
        public Thread getThread() {
            return mThread;
        }
        //结束looper循环
        public void quit() {
            // 创建一个空的message,它的target为NULL,表示结束循环消息  
            Message msg = Message.obtain();
            // 发出消息  
            mQueue.enqueueMessage(msg, 0);
    }
    

    (3)MessageQueue源码
    MessageQueue.enqueueMessage将一个Message放入到消息队列MessageQueue中

        boolean enqueueMessage(Message msg, long when) {
            //code...
            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) {
                    //消息队列无消息将当前插入的消息作为队头,若此时消息队列处于等待状态,则唤醒
                    msg.next = p;
                    mMessages = msg;
                    needWake = mBlocked;
                } else {
                    //消息队列里有消息,则根据消息创建的时间 插入到队列中
                    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;
        }
    

    MessageQueue.next从消息队列MessageQueue中阻塞式地取出一个Message

    Message next() {
            //code...
            //确定消息队列中是否还有消息。从而决定消息队列应处于出队消息状态还是等待状态
            int nextPollTimeoutMillis = 0;
            for (;;) {
                if (nextPollTimeoutMillis != 0) {
                    Binder.flushPendingCommands();
                }
                //若是nextPollTimeoutMillis为-1,此时消息队列处于等待状态
                nativePollOnce(ptr, nextPollTimeoutMillis);
    
                synchronized (this) {
                    // Try to retrieve the next message.  Return if found.
                    final long now = SystemClock.uptimeMillis();
                    Message prevMsg = null;
                    Message msg = mMessages;
                    //从消息队列中取出消息:按创建Message对象的时间顺序
                    if (msg != null && msg.target == null) {
                        // Stalled by a barrier.  Find the next asynchronous message in the queue.
                        do {
                            prevMsg = msg;
                            msg = msg.next;
                        } while (msg != null && !msg.isAsynchronous());
                    }
                    if (msg != null) {
                        if (now < msg.when) {
                            // Next message is not ready.  Set a timeout to wake up when it is ready.
                            nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                        } else {
                            // Got a message.
                            mBlocked = false;
                            if (prevMsg != null) {
                                prevMsg.next = msg.next;
                            } else {
                                mMessages = msg.next;
                            }
                            msg.next = null;
                            if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                            msg.markInUse();
                            return msg;
                        }
                    } else {
                        // No more messages.
                        //消息队列中已无消息,则将nextPollTimeoutMillis参数设为-1。下次循环时,消息队列则处于等待状态
                        nextPollTimeoutMillis = -1;
                    }
                    //code...
                }
                //code...
            }
        }
    

    (4)Message源码

        //Message内部维护了一个Message池,用于Message消息对象的复用
        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;
                }
            }
            //若池内无消息对象可复用,则还是用关键字new创建
            return new Message();
        }
    

    相关文章

      网友评论

          本文标题:Handler + Looper + MessageQueue详

          本文链接:https://www.haomeiwen.com/subject/tmhqrxtx.html