Android消息机制之 Looper 消息循环

概述

前面 讲了消息机制中的 MessageQueue,Looper 与 MessageQueue 的关联是 Looper 会通过轮询,不断从 MessageQueue 中获取新消息,如果有新消息就会立即处理,没有新消息就会阻塞。

示例

子线程创建Handler,需要绑定对应的 Looper,不然会报错:

       new Thread(new Runnable() {
                    @Override
                    public void run() {
                       //方法一:创建子线程的 Looper
                        //需要加Looper.prepare(); 不然会报错
                        Looper.prepare();
                        Handler handler = new Handler() {
                            @Override
                            public void handleMessage(Message msg) {
                                super.handleMessage(msg);
                                Toast.makeText(getApplicationContext(), "handler msg", Toast.LENGTH_LONG).show();
                            }
                        };
                        handler.sendEmptyMessage(1);
                        //需要加Looper.loop() 开启消息轮询
                        Looper.loop();

                        //方法二:获取主线程的looper,或者说是UI线程的looper
                       /* Handler handler2 = new Handler(Looper.getMainLooper()){
                            @Override
                            public void handleMessage(Message msg) {
                                //super.handleMessage(msg);
                                LogUtils.e("twj124", "handleMessage");
                                Toast.makeText(getApplicationContext(), "handler msg", Toast.LENGTH_LONG).show();
                            }
                        };
                        handler2.sendEmptyMessage(1);*/
                    }
                }).start();

源码

因为一个线程只有一个 Looper 和 一个 MessageQueue,在 Looper 的构造方法中,会初始化该线程对应的 MessageQueue 并获取当前线程:

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

Looper 最重要的方法是loop(),该方法会不断从 MessageQueue 中取消息。

    /**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the loop.
     */
    public static void loop() {
        final Looper me = myLooper();
        //如果没有当前线程没有创建对应的 Looper,就会抛出异常。
        //因此,在子线程中,需要调用 Looper.prepare()  和 Looper.loop()
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        //获取到与Looper 绑定的 MessageQueue 
        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
            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 slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            final long end;
            try {
                //msg.target实际为发送这条消息的Handler对象
                //dispatchMessage:与Looper对象在同一个线程,而handleMessage()与Handler创建在同一个线程,因此实现了线程切换
                //这样,Handler发送的消息最终会交给它的dispatchMessage来处理,该方法最后会调用handleMessage()来处理
                msg.target.dispatchMessage(msg);
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (slowDispatchThresholdMs > 0) {
                final long time = end - start;
                if (time > slowDispatchThresholdMs) {
                    Slog.w(TAG, "Dispatch took " + time + "ms on "
                            + Thread.currentThread().getName() + ", h=" +
                            msg.target + " cb=" + msg.callback + " msg=" + msg.what);
                }
            }

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

可以看到,loop()方法是一个死循环,只有当 MessageQueue 的 next() 方法为 null 时,才会结束循环。那么MessageQueue 的 next() 什么时候回返回 null 呢?我们看 next()方法:

    //MessageQueue#next()
    Message next() {
        // Return here if the message loop has already quit and been disposed.
        // This can happen if the application tries to restart a looper after quit
        // which is not supported.
        final long ptr = mPtr;
        if (ptr == 0) {
            return null;
        }
        //省略。。。
   }
    //Looper#quit()
     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);
        }
    }

可以看到,当 Looper 的 quit() / quitSafely()方法被调用时,消息队列就会被标记为退出状态( mQuitting = true),消息队列的 next()就会返回 null。因此,在子线程中,如果手动创建了 Looper,那么在完成所有任务后应该调用quit()来终止消息循环,否则这个子线程一直处于等待状态,而如果退出 Looper 后,该线程就会立刻终止。所以,在不需要的时候,应该养成良好的编程习惯来终止 Looper。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值