"Android Basics" Asynctask learning--How to cancel out Asynctask

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.