首页 > 解决方案 > 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()
        }
    }
}

标签: android

解决方案


您需要使用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
        }
    }
}

推荐阅读