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

前端之家收集整理的这篇文章主要介绍了android-如何在Kotlin中为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?) {


        }
最佳答案
有多种方法可以实现此目的.以下是两个示例:

>使用HttpURLConnection添加超时:

try {
    connection.connectTimeout = 5000 // We all timeout here
    connection.connect()
    text = connection.inputStream.use { it.reader().use{reader -> reader.readText()} }
} finally{
    connection.disconnect()
}

>使用Handler&手动断开连接可运行(我们也可以使用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()
}

编辑O.P .:

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

//We pass context to Activity/Fragment to display alert dialog
inner class TestApiCall(private val context: Context?) : AsyncTask<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")

猜你在找的Android相关文章