AwesomeAndroid

AwesomeAndroid

Posted by 袁平 on November 24, 2018

前言

记录一些有趣的Android知识, 内容不限~


正文


子线程更新UI

考虑如下代码:

注: MainActivityLayout布局只有一个idmain_textTextView

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initView()
    }

    private fun initView() {
//        Thread { main_text.text = "World" }.start() // 更新UI成功
        Thread {
            sleep(200)
            main_text.text = "World" // 更新UI失败(崩溃0)
        }.start()
    }
}

如上代码中, 在第二个子线程中跟新UI的时候失败了, 报错: Only the original thread that created a view hierarchy can touch its views; 即常见的不能在子线程中更新UI; 但是在第一个子线程中跟新UI成功了, 原因是: 线程的检查是在ViewRootImp中的checkThread()中, 但是在onCreate()中, 此时ViewRootImp还没有创建, 所以此时无法checkThread(), 实际上, ViewRootImp的创建是在onResume()方法回调之后, 在WindowManagerGlobaladdView中创建的; 所以如果这里的initView即使是在onResume()中调用也是同样的现象