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 AsyncTask won't stop when cancelled, why?

I've an AsyncTask that I shut down in the Activity's onPause lifecycle event, so it doesn't run when someone leaves the app, but it keeps going despite this. I added some tracing and this snippet shows the problem.

    Trace.d(TAG,"Task state: " + myTask.getStatus() );
    myTask.cancel(true);
    Trace.d(TAG,"Task state: " + myTask.getStatus() );

Outputs:

Task state: RUNNING
Task state: RUNNING

Why is the cancel() method not having any effect on the state of the task? I notice the docs say the cancel method will "attempt" to stop the task, but under what circumstances will it fail? The task is definitely running as it is outputting log output every ten seconds, and as you can see above its status is returned as running.

Update: I added tracing to show me the isCancelled() state as well and that DOES change. So the call to cancel(true) is changing the cancelled state from false to true, but apparently having no effect on the Status, or stopping the thread.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Keep in mind that your Activity and your AsyncTask are two separate threads. So even if you cancel the AsyncTask, the code to cancel the task may not run yet! That's why you are seeing the AsyncTask still running even after fixing your bug. I don't think the status will change until doInBackground() in your AsyncTask has completed. (So make sure you're checking isCancelled() and returning early when you've been cancelled!)


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

...