这是我的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?) {
}
答案 0 :(得分:2)
有多种方法可以实现此目的。以下是两个示例:
使用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
和Runnable
手动断开连接(我们也可以使用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")