Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

Not only that. AsyncTask causes some irregular duties like for example if any activity destroyed or life cycle of that is over the asynctask in this may still doing work in the background thread.For this purpose API developers have introduces Volly framework. you can find some more details here http://bon-app-etit.blogspot.in/2013/04/the-dark-side-of-asynctask.html

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top