What is the proper way of using asynctasks? Let's say a user enters an activity, and asynctask starts, and while the asynctask is running the user decides to navigate to another page.
Methods of AsyncTask onPreExecute() − Before doing background operation we should show something on screen like progressbar or any animation to user. we can directly comminicate background operation using on doInBackground() but for the best practice, we should call all asyncTask methods .
We use Android AsyncTask to perform these heavy tasks in the background on a separate thread and return the results back to the UI thread in order to prevent this. As a result, the UI thread is always responsive when AsyncTask is used in an Android application.
In Android, AsyncTask (Asynchronous Task) allows us to run the instruction in the background and then synchronize again with our main thread. This class will override at least one method i.e doInBackground(Params) and most often will override second method onPostExecute(Result).
AsyncTask must be subclassed to be used. The subclass will override at least one method ( doInBackground(Params...) ), and most often will override a second one ( onPostExecute(Result) .)
The asynctask will keep running. The asynctask might die as the Android OS tries to reclaim memory when it's running low. If you don't care that the async task might not finish, then maybe this doesn't matter, but it's bad practice.
Also, maybe when the async task dies depending on how you're storing/handling the result, you risk trying to edit an Activity/objects in that activity that are no longer there, resulting in nullpointerexceptions and other bad things. The proper way of doing this would be to start a service from your activity and start an asynctask from the service. You should follow one of the design patterns outlined in this talk given at Google IO 2010:
Android REST Client Design Patterns
That talk interesting but is hard to follow and gives no code, so here's a good tutorial that I used to learn this stuff:
Downloading Data with Services
Also, android will manage a threadpool of your asynch tasks for you (i believe it will start killing them when you have more than 5 in your process), you don't have to kill them. check out the answer here:
How AsyncTasks die
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With