重复利用同一AsyncTask的最佳解决方案? [英] Optimal solution for utilizing the same AsyncTask repeatedly?
问题描述
我知道AsyncTask只能运行一次.我知道一种解决方法,但是我需要AsyncTask中的一个使用复杂(?)进程的变量.这是我用于调用AsyncTask的代码
I know that an AsyncTask can be run only once. I know a way around that, but I need a variable from the AsyncTask that uses complicated(?) processes. This is my code for calling the AsyncTask
val thr=NewTask()
thr.delegate = this
button.setOnClickListener {
thr.execute()
}
NewTask.doOnBackground()只是将请求发送到URL的普通方法. onPostExecute()有点不同:
NewTask.doOnBackground() is just a normal method sending the request to the URL. onPostExecute() is a bit different:
public override fun onPostExecute(result: String?) {
//super.onPostExecute(result)
delegate!!.processFinish(result!!)
}
委托是AsyncResponse的变量吗?这是一个包含processFinish抽象方法的接口,该方法采用字符串,不返回任何内容.
with delegate being a variable of AsyncResponse? which is an interface containing processFinish abstract method taking a string and returning nothing.
我的问题是,如何在仍然获得响应的同时重复运行AsyncTask?预先感谢.
My question is, how can I run the AsyncTask repeatedly while still getting the response? Thanks in advance.
推荐答案
最后,我决定使用协程.协程易于使用,比AsyncTask容易得多.我不知道为什么我怕他们.这是我使用的代码:
Finally, I settled on using coroutines with this. Coroutines are easy to use, much easier than AsyncTask. I don't know why I was scared of them. Here is the code I used:
class CoRoutine{
suspend fun httpGet(url: String = "https://boogle.org): String {
val arr = ArrayList<String>()
withContext(Dispatchers.IO) {
val url = URL(url)
with(url.openConnection() as HttpURLConnection) {
requestMethod = "GET" // optional default is GET
//arr.add(responseCode)
inputStream.bufferedReader().use {
it.lines().forEach { line ->
//println(line)
arr.add(line as String)
}
}
}
}
return arr.get(0)
}
}
这篇关于重复利用同一AsyncTask的最佳解决方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!