Looper、Handler、Message三者关系

自我理解Looper、Handler、Message的关系,一般面试的必答题,涉及到Android的异步消息处理机制。

  • 简单的来说,我们一般用Handler实现异步消息处理。为什么会用到Handler?
    子线程不允许访问 UI(在多线程情况下,UI控件会处于不可预期的状态)
    Handler采用单线程模型,切换到UI线程去操作UI,解决以上问题。所以要明白Handler的消息机制。
  • Looper:在主线程启动中(ActivityThread)中会调用Looper.prepareMainLooper(); 方法:
 public static void main(String[] args) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
        SamplingProfilerIntegration.start();

        // CloseGuard defaults to true and can be quite spammy.  We
        // disable it here, but selectively enable it later (via
        // StrictMode) on debug builds, but using DropBox, not logs.
        CloseGuard.setEnabled(false);

        Environment.initForCurrentUser();

        // Set the reporter for event logging in libcore
        EventLogger.setReporter(new EventLoggingReporter());

        // Make sure TrustedCertificateStore looks in the right place for CA certificates
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);

        Process.setArgV0("<pre-initialized>");

        //这里直接掉用Looper类的静态方法
        Looper.prepareMainLooper();

        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        //调用Looper类静态方法
        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

先看Looper.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();
        }
    }

主要看下prepare(false);方法里面:

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

方法中new Looper(boolean) 执行Looper的构造方法,创建了Looper。
sThreadLocal是一个ThreadLocal对象,可以在一个线程中存储变量。可以看到,将一个Looper的实例放入了ThreadLocal,并且在之前判断了sThreadLocal是否为null,否则抛出异常。这也就说明了Looper.prepare()方法不能被调用两次,同时也保证了一个线程中只有一个Looper实例。

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

这里创建了MessageQueue的实例。

回看ActivityThread中还调用Looper.loop()方法,众所周知的Looper类中的两个方法在ActivityThread中间接调用(不单单只有ActivityThread才能调用),现在看看Looper.loop方法做了什么:

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

首先看下第二行final Looper me = myLooper();myLooper做了什么。

public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

还记得前面初始化的时候prepare()中将一个Looper实例放入到ThreadLocal中,这里是取出Looper。

再看第四行final MessageQueue queue = me.mQueue; 初始化中调用构造函数中,创建了MessageQueue的实例,这里赋值给局部变量 queue。

再往下有一个for(;;)的死循环,有什么作用了?
循环体内第一行,调用了message.next方法,取出消息队列中的消息,为空没有消息就阻塞。
有消息的时候就执行msg.target.dispatchMessage(msg); 把消息交给msg.target去执行dispatchMessage方法处理消息,而msg.target就是Handle了。查看Message源码中Handler target; target就是指的Handler,我们经常使用handler的时候,回调用handler.sendMessager方法,最后深入会走Handler类如下代码:

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

当我们使用Handler时候,Handler mHandler = new Handler() {……}看看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;
    }

其中调用了比较熟悉的mLooper = Looper.myLooper(); 获取存储的Looper实例赋值。mQueue = mLooper.mQueue; 获取存储的MessageQueue实例赋值。比如使用Handler方法:

private Handler mHandler = new Handler()  
    {  
        public void handleMessage(android.os.Message msg)  
        {  
            switch (msg.what)  
            {  
            case value:  

                break;  

            default:  
                break;  
            }  
        };  
    };  

看到这里是不是发现Looper、Handler、Message已经绑定在一起了。
总结如下:
Looper:是一个消息分发器,在主线程创建的时候就会创建一个Looper对象;
MessageQueue :消息队列,是由Message组成的一个队列;
Handler :获取到Message,然后执行动作,可以在主线程和子线程中互相传递数据;

用一张很常见的图总结:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值