为什么是有可能的Andr​​oid 5(棒棒堂)上直​​接从其他线程改变UI的意见? [英] Why is it possible on Android 5 (Lollipop) to directly change UI views from other threads?

查看:98
本文介绍了为什么是有可能的Andr​​oid 5(棒棒堂)上直​​接从其他线程改变UI的意见?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下code:

new Thread() {
    @Override
    public void run() {
        myTextView.setText("Some text");
    }
}.start();

在pre-棒棒糖机器人,即code使 CalledFromWrongThreadException 例外,但为什么它的工作原理罚款棒棒堂机器人?

On pre-Lollipop androids, that code causes the CalledFromWrongThreadException exception, but why does it work fine on Lollipop androids?

测试环境:Genymotion模拟器运行Android 5.1

Testing environment: Genymotion emulator running Android 5.1

在code是片段类的<​​code> onCreateView()方法内。

The code was inside the onCreateView() method of the Fragment class.

推荐答案

这是个时机问题,例如中插入的onCreate您的code()会的没有的崩溃对三星Galaxy应用程序S3也没有的Nexus 7 2013年的Andr​​oid 5.1。但是,如果修改了code,使得它不断更新的TextView的:

It's a matter of timing, for example inserting your code in onCreate() would not crash the app on Samsung Galaxy S3 nor Nexus 7 2013 on Android 5.1. However, if you modify the code such that it's constantly updating the TextView:

    new Thread() {
        @Override
        public void run() {
            int count = 0;
            while (true) {
                SystemClock.sleep(16);
                ((TextView) findViewById(R.id.test)).setText(count++ + "");
            }
        }
    }.start();

然后,它会崩溃在18〜呼叫,当 TextView.setText(字符串)无意中调用 View.requestLayout(); 最终调用 ViewRootImpl.requestLayout(),实际上并检查正确的线程。 这可能是做是为了减少线程的检查,以最小的开销

Then it'll crash on ~18th call, when TextView.setText(String) inadvertently calls View.requestLayout(); which eventually calls ViewRootImpl.requestLayout() that actually does check for correct thread. This is probably done to reduce the overhead of thread checking to a minimum.

这篇关于为什么是有可能的Andr​​oid 5(棒棒堂)上直​​接从其他线程改变UI的意见?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆