kotlin - 为什么我的代码不呈现界面或根本不工作?
问题描述
添加条件为 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/Java 中创建一个新线程,你不应该重写start()
,而是run()
函数。run()
是线程的“主体”。start()
用于调度线程启动。
结果,您并没有真正在MyThread
. 它在主线程上执行,无限期地阻塞它。
另外,请注意,即使在活动关闭后,该线程也会执行。每次打开MainActivity
一个新线程都会启动,泄漏资源。
推荐阅读
- r - ggplot2 - 因子水平累积计数的 geom_line
- java - 如何设置 Firebase Storage 存储订阅???所以用户使用我的应用程序,但他们必须为额外的存储付费
- batch-file - 如何批量组合变量和文本字符串?
- c - 这是在 C 中进行标记指针的可移植方式吗?
- python - 使用变量名的嵌套字典项的 Django 模板语法
- json - Xamarin 形式。无法在列表中显示 json 对象
- json - 将数组转换为以 ID 作为索引的 JSON (MongoDB / Express)
- sql - 连接两个表,其中一些列合并,其他列必须为空
- javascript - jQuery - 重定向到从 URL 加载()内容后如何获取最终链接?
- c# - c#UserControl构造函数不会按预期抛出异常