android-如何在Kotlin中为AsyncTask添加超时

前端之家收集整理的这篇文章主要介绍了android-如何在Kotlin中为AsyncTask添加超时 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我是科特林的初学者.
我正在使用AsyncTask从API执行JSON数据.我想在一段时间后添加一个超时,以防用户的数据连接非常慢或参差不齐,然后向用户显示一个警告对话框,当您按下按钮时说“抱歉,您的互联网连接不正确”单击关闭应用程序.

这是我的AsyncTask代码

  1. inner class Arr : AsyncTask<String,String,String>(){
  2. }
  3. // for build connection
  4. override fun doInBackground(vararg url: String?): String{
  5. var text : String
  6. val connection = URL(url[0]).openConnection() as HttpURLConnection
  7. try {
  8. connection.connect()
  9. text = connection.inputStream.use { it.reader().use{reader -> reader.readText()} }
  10. } finally{
  11. connection.disconnect()
  12. }
  13. return text
  14. }
  15. override fun onPostExecute(result: String?) {
  16. super.onPostExecute(result)
  17. handleJson(result)
  18. }
  19. override fun onProgressUpdate(vararg text: String?) {
  20. }
最佳答案
有多种方法可以实现此目的.以下是两个示例:

>使用HttpURLConnection添加超时:

  1. try {
  2. connection.connectTimeout = 5000 // We all timeout here
  3. connection.connect()
  4. text = connection.inputStream.use { it.reader().use{reader -> reader.readText()} }
  5. } finally{
  6. connection.disconnect()
  7. }

>使用Handler&手动断开连接可运行(我们也可以使用CountDownTimer或其他任何东西实现相同的功能):

  1. try {
  2. connection.connect()
  3. text = connection.inputStream.use { it.reader().use{reader -> reader.readText()} }
  4. // We all timeout here using Handler
  5. Handler().postDelayed(
  6. {
  7. connection.disconnect() // We disconnect manually
  8. },5000 // Timeout value
  9. )
  10. } finally{
  11. connection.disconnect()
  12. }

编辑O.P .:

如果连接超时,请使用下面的类进行API调用并向用户显示警报.

  1. //We pass context to Activity/Fragment to display alert dialog
  2. inner class TestApiCall(private val context: Context?) : AsyncTask<String,String?>() {
  3. // for build connection
  4. override fun doInBackground(vararg url: String?): String? {
  5. var text: String? = null
  6. val connection = URL(url[0]).openConnection() as HttpURLConnection
  7. try {
  8. connection.connect()
  9. text = connection.inputStream.use { it.reader().use { reader -> reader.readText() } }
  10. handleTimeout { timedOut ->
  11. if (timedOut) {
  12. text = null
  13. connection.disconnect()
  14. print("Timeout Executed")
  15. }
  16. }
  17. } finally {
  18. connection.disconnect()
  19. }
  20. return text
  21. }
  22. private fun handleTimeout(delay: Long = 5000,timeout: (Boolean) -> Unit) {
  23. Handler(Looper.getMainLooper()).postDelayed({
  24. timeout(true)
  25. },delay)
  26. }
  27. override fun onPostExecute(result: String?) {
  28. super.onPostExecute(result)
  29. if (result != null) {
  30. //Handle result here
  31. print("Result --> $result")
  32. } else {
  33. //Result is null meaning it can be timed out
  34. context?.let { ctx ->
  35. val alertDialog = AlertDialog.Builder(ctx)
  36. alertDialog.setTitle("Some title here")
  37. alertDialog.setMessage("Notifying user about API error")
  38. alertDialog.create().show()
  39. }
  40. }
  41. }
  42. override fun onProgressUpdate(vararg text: String?) {
  43. //Update progress from here
  44. }
  45. }

通过传递上下文和“您的API URL”从Activity / Fragment调用它:

  1. TestApiCall(context).execute("https://jsonplaceholder.typicode.com/todos/1")

猜你在找的Android相关文章