如何在Kotlin中为AsyncTask添加超时

时间:2019-03-30 06:58:16

标签: android kotlin android-asynctask

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

这是我的AsyncTask代码:

 inner class Arr : AsyncTask<String, String, String>(){



        }

        //        for build connection
        override fun doInBackground(vararg url: String?): String{

            var text : String
            val connection = URL(url[0]).openConnection() as HttpURLConnection

            try {
                connection.connect()
                text = connection.inputStream.use { it.reader().use{reader -> reader.readText()} }


            } finally{

                connection.disconnect()

            }
            return text
        }

        override fun onPostExecute(result: String?) {

            super.onPostExecute(result)
            handleJson(result)


        }

        override fun onProgressUpdate(vararg text: String?) {


        }

1 个答案:

答案 0 :(得分:2)

有多种方法可以实现此目的。以下是两个示例:

  1. 使用HttpURLConnection添加超时:

    try {
        connection.connectTimeout = 5000 // We all timeout here
        connection.connect()
        text = connection.inputStream.use { it.reader().use{reader -> reader.readText()} }
    } finally{
        connection.disconnect()
    }
    
  2. 使用HandlerRunnable手动断开连接(我们也可以使用CountDownTimer或其他任何东西实现相同的功能):

    try {
        connection.connect()
        text = connection.inputStream.use { it.reader().use{reader -> reader.readText()} }
        // We all timeout here using Handler
        Handler().postDelayed(
            {
                connection.disconnect() // We disconnect manually
            },
            5000 // Timeout value
        )
    } finally{
        connection.disconnect()
    }
    

编辑收件人:

使用下面的类进行 API调用,并在连接超时时向用户显示警报。

//We pass context to Activity/Fragment to display alert dialog
inner class TestApiCall(private val context: Context?) : AsyncTask<String, String, String?>() {

    //        for build connection
    override fun doInBackground(vararg url: String?): String? {
        var text: String? = null
        val connection = URL(url[0]).openConnection() as HttpURLConnection

        try {
            connection.connect()
            text = connection.inputStream.use { it.reader().use { reader -> reader.readText() } }
            handleTimeout { timedOut ->
                if (timedOut) {
                    text = null
                    connection.disconnect()
                    print("Timeout Executed")
                }
            }
        } finally {
            connection.disconnect()
        }
        return text
    }

    private fun handleTimeout(delay: Long = 5000, timeout: (Boolean) -> Unit) {
        Handler(Looper.getMainLooper()).postDelayed({
            timeout(true)
        }, delay)
    }

    override fun onPostExecute(result: String?) {
        super.onPostExecute(result)
        if (result != null) {
            //Handle result here
            print("Result --> $result")
        } else {
            //Result is null meaning it can be timed out
            context?.let { ctx ->
                val alertDialog = AlertDialog.Builder(ctx)
                alertDialog.setTitle("Some title here")
                alertDialog.setMessage("Notifying user about API error")
                alertDialog.create().show()
            }
        }
    }

    override fun onProgressUpdate(vararg text: String?) {
        //Update progress from here
    }
}

通过传递上下文“您的API URL” Activity/Fragment进行调用:

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