android - AsyncTask 的新实例未执行
问题描述
这个 Kotlin 例程是我从各种论坛示例中拼凑而成的,但仅在第一次调用时才有效。
class myClass: Activity(), myInterface {
override fun onCreate(...) {
...
}
override fun myCallback(response: String) {
myReturningFunction(response)
}
fun myCallingFunction() {
...
...
val myServer = myObject
myServer.myObjectInit(this, stringData)
//myServer.execute(stringData)
}
}
interface myInterface {
fun myCallback(response: String)
}
object myObject : AsyncTask<String, String, String>() {
var thisInterface: myInterface? = null
fun myObjectInit(thatInterface: myInterface, stringData: String) {
thisInterface = thatInterface
//this.executeOnExecutor(THREAD_POOL_EXECUTOR)
this.execute(stringData)
}
override fun doInBackground(vararg params: String): String? {
var response: String = ""
//return try {
try {
params.first().let {
val url = URL("- web service URL -")
val urlConnect = url.openConnection() as HttpURLConnection
with(urlConnect) {
requestMethod = "POST"
readTimeout = 5000
connectTimeout = 5000
doInput = true
doOutput = true
setRequestProperty("Content-Type", "application/json")
setRequestProperty("Accept", "application/json")
setRequestProperty("Charset", "utf-8")
val jsonByteData = it.toByteArray(Charsets.UTF_8)
outputStream.write(jsonByteData, 0, jsonByteData.size)
outputStream.flush()
outputStream.close()
//inputStream.bufferedReader().readText()
response = inputStream.bufferedReader().readText()
inputStream.close()
disconnect()
}
}
} catch (e: Exception) {
response = ""
}
return response
}
override fun onPostExecute(result: String?) {
when {
result != null -> {
thisInterface?.myCallback(result)
}
else -> {
println("null response")
}
}
}
}
我实例化了 AsyncTask 对象的一个副本并执行它,当我通过接口成功接收到响应时,我实例化另一个副本 ( val myServer = myObject
) 以进行后续调用,但这一次它抛出了这个错误:
Cannot execute task: the task is already running.
我尝试了很多方法,关闭输入流,断开与服务器的连接,取消任务,但都不起作用。
我缺少的代码是否有明显问题?
TIA。
解决方案
AsyncTask
只能执行一次。如果要再次执行它,则需要创建第二个。
从文档中:
该任务只能执行一次(如果尝试第二次执行将引发异常。)
您可以做的是子类化AsnycTask
并在每次要执行它时使用一个新实例:
fun startBackgroundTask(){
CustomAsyncTask().execute()
// Or in your case:
CustomAsyncTask().myObjectInit(this, "data")
}
class CustomAsyncTask: AsyncTask<String, String, String>(){
var thisInterface: myInterface? = null
fun myObjectInit(thatInterface: myInterface, stringData: String) {
thisInterface = thatInterface
execute(stringData)
}
override fun doInBackground(vararg params: String?): String {
// Do your work.
return ""
}
}
推荐阅读
- java - 相同的 header.jsp 用于不同的 Web 应用程序
- c# - FluentValidation:更新验证器中一些可选属性的验证模型
- java - 如何防止 ContextMenu 关闭?
- django - Django ORM:如何使用带注释字段的过滤器进行聚合?
- swiftui - SwiftUI 中的 Expandable List 只展开一次,不会收缩
- azure-table-storage - 如何使用 Node-Red HTTP 请求节点访问 Azure 表存储 API
- python - Python 子图
- azure - 未找到资源组 null 下的资源“microsoft.insights/actiongroups/HmActionGroup”
- mysql - Rails 使用日期范围和时间范围验证唯一性
- c# - 更改日期格式并将其保留为日期