Click here to Skip to main content
15,896,207 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have use AsnycTask for get Data from Sql Server.
I Create AsnycTask object below method:
C#
new MyAsnycTask().execute(new String[]{"......"});

My Question is:
How to implement OnCancel() in AsnycTask Class , So that we have kill Current AsnycTask object,Because We have multiple time create Object of AsnycTas.
Posted
Updated 4-Sep-12 19:23pm
v2

1 solution

In every AsyncTask, you implement the onCancelled method:

Java
@Override
protected void onCancelled() {
    /*Release your resources, such as closing DB connections, abort downloads in
    progress, etc*/
}


Now, calling cancel() on an AsyncTask will cause onCancelled() instead of onPostExecute() to be executed when doInBackground() is finished. Notice that onCancel isn't immediately called (as said, it's called when doInBackground is finished), but a flag is set, which can be accessed via yourAsyncTask.isCancelled(). This is why it's proper practice (and recommended by Android development guidelines) to periodically check this flag from your doInBackground method, usually in a loop:

Java
@Override
protected Object doInBackground(Object... x) {
    while (!isCancelled()) {
      // Do your work
      return workProcessingResult;
    }
    return null;
 }


Further reading here[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900