Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
416 views
in Technique[技术] by (71.8m points)

android - How to completely kill/remove/delete/stop an AsyncTask

I made an app that downloads videos from our server. The issue is:

When i cancel the downloading i call:

myAsyncTask.cancel(true)

I noticed, that myAsyncTask doesn't stops on calling cancel... my ProgressDialog still goes up and its like jumping from status to status showing me that each time I cancel and start again an AsyncTask by clicking the download button, a new AsyncTask starts... Each time I click download.. then cancel, then again download a separate AsyncTask starts.

Why is myAsynTask.cancle(true) not cancelling my task ? I don't want it anymore on the background. I just want to completely shut it down if I click cancel.

How to do it ?

E D I T:

Thanks to gtumca-MAC, and the others who helped me did it by:

while (((count = input.read(data)) != -1) && (this.isCancelled()==false)) 
{
    total += count;
    publishProgress((int) (total * 100 / lenghtOfFile));
    output.write(data, 0, count);
}

Thanks!!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

AsyncTask does not cancel process on

myAsynTask.cancel(true) 

For that you have to stop it manually.

for example you are downloading video in doInBackground(..) in while/for loop.

protected Long doInBackground(URL... urls) {

         for (int i = 0; i < count; i++) {
          // you need to break your loop on particular condition here

             if(isCancelled())
                  break;             
         }
         return totalSize;
     }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...