Android Handler机制深入解析

Handler是什么

Handler是Android设计者Google设计用于的一套更新UI的机制,也是一套消息处理的机制,我们可以发送消息,也可以通过它来处理消息,Handler在我们的 framework中是非常常见的。
Android 在设计的时候,就封装了一套消息创建、传递、处理机制,如果不遵循这样的机制就不能更新UI信息,并抛出异常信息。

为什么要设计只能通过Handler机制来更新UI呢

其实最根本的目的就是解决多线程并发问题。例如,当我们在一个Activity中执行来多个线程并更新一个UI控件,如果没有这个Handler机制,将可能出现异常情况,我们可以通过加锁的来解决多线程并发问题,但加锁带来的问题就是性能下降。
针对以上的问题,Google设计android时就已经为我们考虑好了,通过遵循Handler机制来解决这个问题。

如何使用

关于如何使用Handler本文就不再叙述了,因为使用起来十分简单,随便Google一下也都有介绍。

原理

那么Handler的原理是什么呢?或者说Google开发者们是如何实现的Handler机制呢?要想弄清楚原理,我们还是从源码中来了解一下吧。
一、 在解读源码之前,我们先认识以下几个Handler机制关键的Class对象。

  • Looper
    1.内部包含一个消息队列 MessageQueue,所有的 Handler 发送的消息都走向(加入)这个消息队列。
    2.Looper.Looper方法,就是一个死循环,不断地从 MessageQueue 取得消息,如果有消息就处理消息,没有消息就阻塞。
  • MessageQueue
    MessageQueue 就是一个消息队列,可以添加消息,并处理消息。
  • Handler
    Handler封装了消息的发送(主要是将消息发送给谁(默认是Handler自己),以及什么时候发送)。Handler内部会跟 Looper 进行关联,也就是说,在 Handler 的内部可以找到 Looper,找到了 Looper 也就找到了 Message。在 Handler 中发送消息,其实就是向 MessageQueue 队列中发送消息。

二、 接下来,我将从如何使用开始给大家深入解析源码。
通常我们使用Handler更新UI时,都是直接去new一个Handler的实例。然后覆写Handler.handleMessage方法,然后在子线程中发送消息通知主线程更新UI。

 Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //更新UI
        }
    };

...
new Thread(new Runnable() {
            @Override
            public void run() {
                //子线程发送message,通知主线程更新UI
                handler.sendEmptyMessage(1);
            }
        }).start();

首先我们来看一下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());
            }
        }

        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构造方法中通过Looper.myLooper()获取到当前线程(UI线程)的Looper对象,那么当前线程如何创建这个Looper对象呢?
其实在Android主线程ActivityThread的入口main方法中,通过调用Looper. prepareMainLooper()方法初始化了Looper对象,并在方法最后调用了Looper.loop()方法开启了这个消息轮训。源码如下:

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.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.loop();

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

于是我们在任意Activity中或者说主线程任意位置new Hander()的时候,通过mLooper = Looper.myLooper();获取当前线程的Looper对象。有同学就好奇了这个Looper.myLooper()方法如何获取到当前的Looper对象的。
接下来,我们就一起看看这个Looper源码。

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

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

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

myLooper()方法中我们注意到sThreadLocal变量,他其实是ThreadLocal<Looper>对象,用于存放这个Looper对象的。在prepare()方法中创建一个Looper对象并存放到这个sThreadLocal.set(new Looper(quitAllowed))
又注意到Looper的构造方法。

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

在这个构造函数中创建了MessageQueue对象。
看到这里,大家应该可以将HandlerLooperMessageQueue三者到关系弄清楚了。接下来再看一下Looper中关键的方法loop()

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

这里通过一个死循环,不断的从消息队列中读取消息,并通过msg.target.dispatchMessage(msg);将message发送给handler自己。

总结

Handler 负责发送消息,Looper 负责接收 Handler 发送的消息,并直接把消息回传给 Handler 自己,MessageQueue就是一个存储消息的容器。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值