@SuppressWarnings({"unchecked", "RawUseOfParameterizedType"}) @Override publicvoidhandleMessage(Message msg){ AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj; switch (msg.what) { case MESSAGE_POST_RESULT: // There is only one result result.mTask.finish(result.mData[0]); break; case MESSAGE_POST_PROGRESS: result.mTask.onProgressUpdate(result.mData); break; } } }
/* * Attempts to cancel execution of this task. This attempt will fail if the task has already completed, already been cancelled, or could not be cancelled for some other reason. If successful, and this task has not started when cancel is called, this task should never run. If the task has already started, then the mayInterruptIfRunning parameter determines whether the thread executing this task should be interrupted in an attempt to stop the task. * Calling this method will result in onCancelled(Object) being invoked on the UI thread after doInBackground(Object[]) returns. Calling this method guarantees that onPostExecute(Object) is never invoked. After invoking this method, you should check the value returned by isCancelled() periodically from doInBackground(Object[]) to finish the task as early as possible. */ publicfinalbooleancancel(boolean mayInterruptIfRunning);
如果你的Task在设计时,考虑了cancel的情况,那么你还需要额外做两件事。
Check a “canceled” flag regularly
Report work results invalid
对于1,如下
1 2 3 4 5 6
doInBackground(..) { // Doing some stuff if (isCanceled()) {..} // Oh noez, we done, clean up for (i < obj.length) if (isCanceled()) {..} // Oh noez, we done, clean up }