我想用
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val json = URL("https://my-api-url.com/something").readText()
simpleTextView.setText(json)
}
但是这个致命的错误发生了
FATAL EXCEPTION: main
Process: com.mypackage.randompackage, PID: 812
java.lang.RuntimeException: Unable to start activity ComponentInfo{ ***.MainActivity}: android.os.NetworkOnMainThreadException
如何从URL链接中简单地读取JSON? async
函数的包不存在。
Android不允许从主线程访问互联网。最简单的方法是在后台线程上打开URL。
像这样的东西:
Executors.newSingleThreadExecutor().execute({
val json = URL("https://my-api-url.com/something").readText()
simpleTextView.post { simpleTextView.text = json }
})
不要忘记在Android Manifest文件中注册Internet权限。
您可以使用协同程序:
val json = async(UI) {
URL("https://my-api-url.com/something").readText()
}
记得向build.gradle添加协同程序:
kotlin {
experimental {
coroutines "enable"
}
}
...
dependencies {
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlinx_coroutines_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$kotlinx_coroutines_version"
...
}
Coroutines很棒。