So I have been handed an Android Application, I noticed that in the Fragment's onStop lifecycle method they did the following:
if(mWorkerTask!=null)
{
AsyncTask.Status taskStatus=mWorkerTask.getStatus();
if(taskStatus==Status.RUNNING||taskStatus==Status.PENDING)
{
mWorkerTask.cancel(true);
}
}
I still don't understand why they did this, is it a requirement to cancel an AsyncTask in the onStop method?
Not necessarily butit is a good practice to stop using any resources allocated to your app
while it was in foreground or doing some useful stuff for the user for example downloading/uploading some data from internet, after it's purpose is finished.
It is the same as closing a file or database
when it is no longer required. Even if you remove the above code from onStop()
, it won't affect your app ( if it is not used by some other process) but canceling asynctask will save memory and cpu cycles eventually battery
.
Hope this helps.