深入理解Android中Handler机制

Posted zhangke3016

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了深入理解Android中Handler机制相关的知识,希望对你有一定的参考价值。

对于一位android开发者来说,对HandlerLooperMessage三个乖宝贝应该再熟悉不过了,这里我们先简单介绍下这三者的关系,之后再用Looper.loop方法做点有意思的事情,加深对运行循环的理解。

一、源码理解HandlerLooperMessage

通常我们在使用Handler时会在主线程中new出一个Handler来接收消息,我们来看下Handler源码:

/**
     * Default constructor associates this handler with the @link Looper for the
     * current thread.
     *
     * If this thread does not have a looper, this handler won't be able to receive messages
     * so an exception is thrown.
     */
    public Handler() 
        this(null, false);
    

在源码注释中说到默认的构造方法创建Handler,会从当前线程中取出Looper,如果当前线程没有Looper,这个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());
            
        
        //获取Looper
        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;
    
 /**
     * Return the Looper object associated with the current thread.  Returns
     * null if the calling thread is not associated with a Looper.
     */
    public static Looper myLooper() 
        return sThreadLocal.get();//从ThreadLocal中获取
    

既然Looper是从ThreadLocal中获取的,那必然有时机要存进去,我们看下Looper是什么时候存进去的:

 /** Initialize the current thread as a looper.
      * This gives you a chance to create handlers that then reference
      * this looper, before actually starting the loop. Be sure to call
      * @link #loop() after calling this method, and end it by calling
      * @link #quit().
      */
    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));
    

也就是说我们在调用Looper. prepare方法时会创建Looper并存入ThreadLocal中,注意默认quitAllowed参数都为true,也就是默认创建的Looper都是可以退出的,我们可以点进去看看:


    private Looper(boolean quitAllowed) 
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    
    //进去MessageQueue.java
       MessageQueue(boolean quitAllowed) 
          mQuitAllowed = quitAllowed;
          mPtr = nativeInit();
        

⚠️注意:MessageQueue的成员变量mQuitAllowed,在调用Looper.quit方法时会进入MessageQueuemQuitAllowed进行判断,可以简单看下源码,后面会再说到:

//MessageQueue.java
void quit(boolean safe) 
        //如果mQuitAllowed为false,也就是不允许退出时会报出异常
        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);
        
    

看到这里我们应该是有疑问的,

  1. 第一个疑问:默认我们调用Looper.prepare方法时mQuitAllowed变量都为true的,那它什么时候为false?又是被如何设为false的?
  2. 第二个疑问:我们在创建Handler时,并没有往ThreadLocal中存Looper,而却直接就取出了ThreadLocal中的Looper,那么这个Looper是什么时候创建并存入的?

这里就要说到ActivityThreadmain方法了。Zygote进程孵化出新的应用进程后,会执行ActivityThread类的main方法。在该方法里会先准备好Looper和消息队列,并将Looper存入ThreadLocal中,然后调用attach方法将应用进程绑定到ActivityManagerService,然后进入loop循环,不断地读取消息队列里的消息,并分发消息。

//ActivityThread
 public static void main(String[] args) 
        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());

        Process.setArgV0("<pre-initialized>");
        //创建主线程的阻塞队列
        Looper.prepareMainLooper();

         // 创建ActivityThread实例
        ActivityThread thread = new ActivityThread();
        //执行初始化
        thread.attach(false);

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

        AsyncTask.init();

        if (false) 
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        
        //开启循环
        Looper.loop();

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

我们看下开启的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
            Printer logging = me.mLogging;
            if (logging != null) 
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            
            //注意这里   msg.target为发送msg的Handler
            msg.target.dispatchMessage(msg);

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

Looper.loop方法内部是个死循环(for(;;))。queue.next();是从阻塞队列里取走头部的Message,当没有Message时主线程就会阻塞。view绘制,事件分发,activity启动,activity的生命周期回调等等都是一个个的Message,系统会把这些Message插入到主线程中唯一的queue中,所有的消息都排队等待主线程的执行。
回过来我们捋一下思路,首先,我们在主线程中创建了Handler,在Handler的构造方法中会判断是否创建了Looper,由于在ActivityThread.main方法中我们初始化了Looper并将其存入ThreadLocal中,所以可以正常创建Handler。(而如果不是在主线程中创建Handler,则需要在创建之前手动调用Looper.prepare方法。)在Looper的构造方法中创建了MessageQueue消息队列用于存取Message。然后Handler.sendMessage发送消息,在queue.enqueueMessage(msg, uptimeMillis)方法中将Message存入MessageQueue中,并最终在Loop.loop循环中取出消息调用msg.target.dispatchMessage(msg);也就是发送消息的HandlerdispatchMessage方法处理消息,在dispatchMessage最终调用了handleMessage(msg);方法。这样我们就可以正常处理发送到主线程的消息了。

二、用Looper搞事情

  1. 异步任务时阻塞线程,让程序按需要顺序执行
  2. 判断主线程是否阻塞
  3. 防止程序异常崩溃

1. 异步任务时阻塞线程,让程序按需要顺序执行
在处理异步任务的时候,通常我们会传入回调来处理请求成功或者失败的逻辑,而我们通过Looper处理消息机制也可以让其顺序执行,不使用回调。我们来看下吧:

    String a = "1";
    public void click(View v)
        new Thread(new Runnable() 
            @Override
            public void run() 
                //模拟耗时操作
                SystemClock.sleep(2000);
                a = "22";
                mHandler.post(new Runnable() 
                    @Override
                    public void run() 
                        mHandler.getLooper().quit();
                    
                );
            
        ).start();

        try
            Looper.loop();
        catch (Exception e)
        
       Toast.makeText(getApplicationContext(),a,Toast.LENGTH_LONG).show();
    

当点击按钮的时候我们开启线程处理耗时操作,之后调用Looper.loop();方法处理消息循环,也就是说主线程又开始不断的读取queue中的Message并执行。这样当执行mHandler.getLooper().quit();时会调用MessageQueuequit方法:

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

这个就到了之前我们分析的变量mQuitAllowed,主线程不允许退出,这里会抛出异常,而最终这段代码是在Looper.loop方法中获取消息调用msg.target.dispatchMessage执行的,我们将Looper.loop的异常给捕获住了,从而之后代码继续执行,弹出Toast。

2. 判断主线程是否阻塞
一般来说,Loop.loop方法中会不断取出Message,调用其绑定的Handler在UI线程进行执行主线程刷新操作。

            if (logging != null) 
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            
            //注意这里   msg.target为发送msg的Handler
            msg.target.dispatchMessage(msg);

            if (logging != null) 
                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
            

也就是这里,基本上可以说msg.target.dispatchMessage(msg);我们可以根据这行代码的执行时间来判断UI线程是否有耗时操作。

msg.target.dispatchMessage(msg);前后,分别有logging判断并打印>>>>> Dispatching to<<<<< Finished to的log,我们可以设置logging并打印相应时间,基本就可以判断消耗时间。

          Looper.getMainLooper().setMessageLogging(new Printer() 
            private static final String START = ">>>>> Dispatching";
            private static final String END = "<<<<< Finished";

            @Override
            public void println(String x) 
                if (x.startsWith(START)) 
                    //开始
                
                if (x.startsWith(END)) 
                   //结束
                
            
        );

3. 防止程序异常崩溃
既然主线程异常事件最终都是在Looper.loop调用中发生的,那我们在Looper.loop方法中将异常捕获住,那主线程的异常也就不会导致程序异常了:

 private Handler mHandler = new Handler();
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_test);

        mHandler.post(new Runnable() 
            @Override
            public void run() 
               while (true)
                   try
                       Looper.loop();
                   catch (Exception e)
                   
               
            
        );
    
    public void click2(View v)
        int a = 1/0;//除数为0  运行时报错
    

主线程的所有异常都会从我们手动调用的Looper.loop处抛出,一旦抛出就会被trycatch捕获,这样主线程就不会崩溃了。此原理的开源项目:Cockroach,有兴趣可以看下具体实现。

以上是关于深入理解Android中Handler机制的主要内容,如果未能解决你的问题,请参考以下文章

带你深入理解Android Handler机制

深入理解Android Handler机制(深入至native层)

深入理解Android Handler机制(深入至native层)

Android IntentService源码理解 及 HandlerThread构建消息循环机制分析

Android :安卓学习笔记之 Handler机制 的简单理解和使用

Android Handler 机制:Hander 机制深入探究问题梳理