How to cancel AsyncTask at the end of an operation?

In my work, I use several AsyncTask classes.

How to cancel AsyncTask at the end of an operation?

+4
source share
3 answers

I don’t understand if your β€œcancel” means rollback, but you have the cancel method of the AsyncTask class.

+2
source

I think the best place for this is onStop

 protected void onStop() { super.onStop(); /* * The device may have been rotated and the activity is going to be destroyed * you always should be prepared to cancel your AsnycTasks before the Activity * which created them is going to be destroyed. * And dont rely on mayInteruptIfRunning */ if (this.loaderTask != null) { this.loaderTask.cancel(false); } } 

in my Task i, check as often as possible if the cancellation was triggered

 protected String doInBackground(String... arg0) { if (this.isCancelled()) { return null; } } 

and, of course, do not forget to delete data that can be returned, since there is no longer any action to get it

 protected void onPostExecute(List<UserStatus> result) { if(!this.isCancelled()) { //pass data to receiver } } 
+6
source

An asynchronous thread is stored in the thread pool for future AsyncTask events. You cannot delete them.

+2
source

Source: https://habr.com/ru/post/1305358/


All Articles