Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Proper way of using AsyncTasks?

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.

  • What's gonna happen to anynctask? is it gonna run until it's done?
  • Am I responsible for stopping this asynctask somehow?
like image 373
aryaxt Avatar asked Oct 04 '11 22:10

aryaxt


People also ask

Which of the following is the correct to use AsyncTask?

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 .

Can we use AsyncTask in Android?

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.

Why AsyncTask is used in Android?

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).

What method must be overridden for using AsyncTask?

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) .)


1 Answers

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

like image 79
Sam Dozor Avatar answered Sep 23 '22 22:09

Sam Dozor