深入理解Android中Handler机制

Looper

对于一位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的?
  1. 第二个疑问:我们在创建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. 异步任务时阻塞线程,让程序按需要顺序执行
  1. 判断主线程是否阻塞
  2. 防止程序异常崩溃

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处抛出,一旦抛出就会被try{}catch捕获,这样主线程就不会崩溃了。此原理的开源项目:Cockroach,有兴趣可以看下具体实现。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 151,511评论 1 330
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 64,495评论 1 273
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 101,595评论 0 225
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 42,558评论 0 190
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 50,715评论 3 270
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 39,672评论 1 192
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,112评论 2 291
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 29,837评论 0 181
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 33,417评论 0 228
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 29,928评论 2 232
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,316评论 1 242
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 27,773评论 2 234
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,253评论 3 220
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,827评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,440评论 0 180
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 34,523评论 2 249
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 34,583评论 2 249

推荐阅读更多精彩内容