0
通常,我有一個AsyncTask
我想取消它。在其doInBackground
方法中,我有幾個Thread.sleep
方法,他們之間我檢查是否AsyncTask#cancel
與isCancelled()
調用。取消AsyncTask遇到Thread.sleep
這裏的問題:如果我在doInBackground
方法有Thread.sleep
,該AsyncTask#onCancelled()
將不會被調用。如果所有Thread.sleep
都被刪除,則調用AsyncTask#onCancelled()
。 什麼使這發生
這是演示的定義。
inner class DemoAsyncTask() : AsyncTask<String, Int, String>() {
// var isRunning = true
override fun doInBackground(vararg params: String?): String? {
Log.i(TAG, "##AsyncTask doing something...")
var i = 0
val TOTAL = 100000000
var progress = 0
while (i < TOTAL && !isCancelled) {
Log.d(TAG, "doning jobs $i is cancelled $isCancelled")
i++
var currentProgress = i/TOTAL
if (currentProgress > progress) {
progress = currentProgress
publishProgress(progress)
}
}
Log.d(TAG, "doning jobs $i is cancelled $isCancelled")
return "Task done"
}
override fun onPostExecute(result: String?) {
[email protected]?.text = result
}
override fun onProgressUpdate(vararg values: Int?) {
mAsyncTextView?.text = "${mAsyncTextView?.text ?: "Async task..."} progress: ${values?.get(0) ?: 0}"
}
override fun onCancelled() {
Log.i(TAG, "##Task cancelled")
// isRunning = false
[email protected]?.text = "###Task cancelled"
}
}
這doInbackground
可以工作,這原來問題出在哪裏發生的這個樣子的:
if (isCancelled) {
var msg = mHandler.obtainMessage(THREAD_CANCELLED)
mHandler.sendMessage(msg)
return
}
Thread.sleep(2000)
if (isCancelled) {
var msg = mHandler.obtainMessage(THREAD_CANCELLED)
mHandler.sendMessage(msg)
return
}
var msg = mHandler.obtainMessage(THREAD_FINISHED)
mHandler.sendMessage(msg)
謝謝!