android - onPostExecute 协程 kotlin
问题描述
再会!我正在尝试将此代码转换为协程,但对我没有任何作用。你能帮我么?我会非常感谢你
PS我是俄罗斯人,英文不太懂,如有错误请不要严格判断
private inner class GetAddress (val position : Int) : AsyncTask<String, Void, String>() {
override fun doInBackground(vararg strings: String): String? {
try {
val url = "https://maps.googleapis.com/maps/api/geocode/json?address=${strings[0]}&language=RU&key=" + getString(R.string.map_key)
Log.d("JSON", "result: $url")
val urls : URL
try {
urls = URL(url)
val conn = urls.openConnection() as HttpURLConnection
conn.requestMethod = "GET"
conn.connect()
val responseCode = conn.responseCode
if (responseCode == HttpURLConnection.HTTP_OK) {
val br = BufferedReader(InputStreamReader(conn.inputStream))
val sb = StringBuilder()
var line: String? = br.readLine()
while (line != null) {
sb.append(line)
line = br.readLine()
}
val json = sb.toString()
val root = JSONObject(json)
val address =
(root.get("results") as JSONArray).getJSONObject(0).get("formatted_address").toString()
Log.d("response", address)
return address
}
} catch (e: ProtocolException) {
e.printStackTrace()
} catch (e: MalformedURLException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
} catch (ex: Exception) { }
return null
}
override fun onPostExecute(s: String) {
try {
toolbarMain.text = s
} catch (e: JSONException) {
e.printStackTrace()
}
}
}
解决方案
您需要使用Activity
本身取消的范围。总而言之,lifecycleScope
应该足够了。然后,您使用Dispatchers.Main
调度程序启动协程以在主线程上恢复协程。withContext()
然后您在Dispatchers.IO
调度程序上获得后台地址。然后分配再次发生在主线程上。
lifecycleScope.launch(Dispatchers.Main) {
toolbarMain.text = withContext(Dispatchers.IO) {
try {
...
(root.get("results") as JSONArray).getJSONObject(0).get("formatted_address").toString()
} catch(ex: Exception) {
null
}
}
}
推荐阅读
- javascript - 当chartJS中的关联值为空时跳过标签
- angularjs - Docker 命令无法在运行时将参数传递给 appConfig.json 文件
- flutter - Flutter/Dart:从 Shared Preferences Widget 获取 URL 以在 Image.Network Widget 中使用
- ios - 通过按钮用日期选择器替换 IOS 键盘
- python - 加快数据帧中数据的过滤
- ios - 我是否在这个嵌套函数中捕获自我?编译器不会发出警告
- c# - 如何将包含编码 HTML 的 json 字符串反序列化为 JObject?
- javascript - Chrome 和 Firefox 中关于 TypeError 的详细错误消息(访问的内容和引用的内容)
- wpf - DecimalUpDown 小数位
- error-handling - 如何暂停KafkaJS消费者并在一段时间后重试