首页 > 解决方案 > 为什么我的代码不呈现界面或根本不工作?

问题描述

添加条件为 true 的 while 循环后(对于无限循环),界面(按钮)甚至在模拟器中启动时都不会绘制。这可能与什么有关?如何解决这个问题?这是我第一次制作应用程序(用于我的智能家居 API)

class MainActivity : AppCompatActivity() {
    lateinit var webview: WebView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        webview = findViewById(R.id.browser)

        MyThread().start()
    }

    inner class MyThread : Thread() {
        override fun start() {
            super.start()
            while (true) {
                runOnUiThread {
                    updateWebView()
                }
                sleep(60000L)
            }
        }
    }
    private fun updateWebView() {
        webview.loadUrl("https://api.site.com/?action=status&device_osversion=${Build.VERSION.SDK_INT}&device_release=${Build.VERSION.RELEASE}&device_device=${Build.DEVICE}&device_model=${Build.MODEL}")
    }
}

标签: kotlin

解决方案


如果你想在 Kotlin/Java 中创建一个新线程,你不应该重写start(),而是run()函数。run()是线程的“主体”。start()用于调度线程启动。

结果,您并没有真正在MyThread. 它在主线程上执行,无限期地阻塞它。

另外,请注意,即使在活动关闭后,该线程也会执行。每次打开MainActivity一个新线程都会启动,泄漏资源。


推荐阅读