In the Android app development process, to prevent the UI thread from clogging, time-consuming work should be done in a separate background thread, where Asynctask is one of the ways. Recently in the case of the need to "stop/Cancel" a asynctask, on the Internet to check some information, here to make a note.
View the Asynctask.java file, which has a cancel () function that can stop a running asynctask by calling Cancel (true).
/*** <p>attempts to cancel execution of this task. This attempt would * fail if the task has already completed, already been cancelled, * or could not being cancelled fo R some other reason. If successful, * and this task have not started when <tt>cancel</tt> was called, * this task should Neve R run. If The task has already started, * then the <tt>mayInterruptIfRunning</tt> parameter determines * whet Her the thread executing this task should is interrupted in * a attempt to stop the task.</p> * * < P>calling This method would result in {@link#onCancelled (Object)} being * invoked the UI thread after {@link#doInBackground (object[])} * returns. Calling this method guarantees that {@link#onPostExecute (Object)} * is never invoked. After invoking this method, you should check the * value returned by {@link#isCancelled ()} periodically from * {@link#doInBackground (object[])} to finish the task as early as * possible.</p> * *@parammayinterruptifrunning <tt>true</tt> If the thread executing this * task should is interrupted; Otherwise, in-progress tasks is allowed * to complete. * * @return<tt>false</tt> If the task could not being cancelled, * typically because it has already complet Ed normally; * <tt>true</tt> otherwise * *@see#isCancelled () *@see#onCancelled (Object)*/ Public Final BooleanCancelBooleanmayinterruptifrunning) {Mcancelled.set (true);
It is worth noting that the call to cancel (true) function requires the following points:
1. The call to cancel will fail when the Asynctask has been completed, or canceled, or for other reasons;
2. If the asynctask has not started executing, call the Cancel (true) function, Asynctask will no longer execute;
3. If Asynctask has already started execution, the parameter mayinterruptifrunning determines whether to stop the task immediately;
4. After calling Cancel (), Doinbackground () does not call OnPostExecute () after completion, but executes oncancelled ();
Here is a simple demo, using two buttons, respectively, for Start & Stop Asynctask.
ImportAndroid.os.AsyncTask;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.os.Bundle;ImportAndroid.util.Log;ImportAndroid.view.View; Public classMainactivityextendsAppcompatactivityImplementsview.onclicklistener{Private Static FinalString TAG = "Asynctasktest"; PrivateTesttask task =NULL; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Findviewbyid (R.ID.BTN1). Setonclicklistener ( This); //start Async Task btn Findviewbyid (r.id.btn2). Setonclicklistener ( This); //stop Async Task Btn } @Override Public voidOnClick (View v) {Switch(V.getid ()) { CaseR.id.btn1:task=NewTesttask (); Task.executeonexecutor (Asynctask.thread_pool_executor); Break; Caser.id.btn2:if(task! = null &&!task.iscancelled () && task.getstatus () = = AsyncTask.Status.RUNNING) {task.cancel (true); Task=NULL; } Break; } } classTesttaskextendsAsynctask<void, Void, void>{@Overrideprotectedvoid Doinbackground (void ... params) {intCount = 5; while(Count > 0) {Count--; if(iscancelled ()) { // iscancelled () determines if Cancel (true) succeeds. log.d (TAG,"Cancel"); Break; } log.d (TAG,"Start Sleep"); Try{Thread.Sleep (2000); //Analog time-consuming Operation } Catch(interruptedexception e) {e.printstacktrace (); } log.d (TAG,"End Sleep"); } return NULL; } @Overrideprotected voidOnPostExecute (Void aVoid) {log.d (TAG,"OnPostExecute"); Super. OnPostExecute (aVoid); } @Overrideprotected voidoncancelled () {log.d (TAG,"Oncancelled"); Super. oncancelled (); } }}
Of course, in the real case, in the Doinbackground () function, unlike the demo, there is only a simple while () loop, so you may need to add a few iscancelled () to end the task in Doinbackground ().
Android Development--Cancel Asynctask