我正在尝试用Kotlin中的Asynctask来完成任务。我想向用户显示对话框消息如果用户在使用时数据连接非常慢或参差不齐,我想在5秒钟的时间后使AsyncTask超时。我的意思是应该在哪里我放对话吗?在finally
中doInBackground
之后?
inner class Arr : AsyncTask<String, String, String>() {
val progressDialog = AlertDialog.Builder(this@MainActivity)
val dialogView = layoutInflater.inflate(R.layout.progress_dialog, null)
val message = dialogView.findViewById<TextView>(R.id.message_id)
val dialog = progressDialog.create()
override fun onPreExecute() {
super.onPreExecute()
dialog.setMessage("please wait")
dialog.setCancelable(false)
dialog.show()
}
// for build connection
override fun doInBackground(vararg url: String?): String {
var text: String
val connection = URL(url[0]).openConnection() as HttpURLConnection
connection.connectTimeout = 300
try {
connection.connect()
text = connection.inputStream.use { it.reader().use { reader -> reader.readText() } }
} finally {
dialog.setMessage("Sorry you dont have proper net connectivity..!\nCheck your internet settings or retry.")
dialog.setCancelable(false)
dialog.show()
}
return text
}
override fun onPostExecute(result: String?) {
super.onPostExecute(result)
handleJson(result)
dialog.dismiss();
}
override fun onProgressUpdate(vararg text: String?) {
}
}