How to properly use the URL with Kotlin Android

梦想与她 提交于 2019-12-06 16:39:36

Android doesn't allow accessing the internet from the main thread. The simplest way around this would be to open the URL on a background thread.

Something like this:

Executors.newSingleThreadExecutor().execute({
            val json = URL("https://my-api-url.com/something").readText()
            simpleTextView.post { simpleTextView.text = json }
        })

Don't forget to register Internet permission in the Android Manifest file.

You could use coroutines:

val json = async(UI) {
        URL("https://my-api-url.com/something").readText()
    }

Remember to add coroutines to 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 are brilliant.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!