我是科特林的初学者.
我正在使用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 dialoginner 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-如何在Kotlin中为AsyncTask添加超时 全部内容,希望文章能够帮你解决android-如何在Kotlin中为AsyncTask添加超时 所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)