我从各种论坛示例中了解到的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,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。