In Asynctask, we have no way to stop the asynchronous task directly, only through the Cancel method to mark Asynctask as the cancel state, that is, the Cancel method simply passes a semaphore, instead of actually cancel the asynchronous task.
So if you want the Cancel method to cancel the asynchronous task directly, you need to detect the current state in Doinbackground: When the state is the cancel state, jump out of the loop immediately.
Using Cancel:
//将task的状态标记为cancel if(task!=null&& task.getStatus() == AsyncTask.Status.RUNNING){ task.cancel(true); }
Detects whether the current status is cancel in an asynchronous task loop and, if cancel, ends the task directly:
class testtask extends asynctask<Void,Integer, Void>{@Overrideprotectedvoid Doinbackground (void ... params) {//TODO auto-generated method stub for(intI=0;i< +; i++) {//If the current mark is cancel, jump out of the loop and return directly if( This. iscancelled ()) {return NULL; }Try{Thread.Sleep ( -); }Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace (); } }return NULL; } }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Android Basics" Asynctask learning--How to cancel out Asynctask