首页 > 解决方案 > 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。

标签: androidkotlinandroid-asynctask

解决方案


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 ""
    }
}

推荐阅读