开发者

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.

  • Wh开发者_Python百科at's gonna happen to anynctask? is it gonna run until it's done?
  • Am I responsible for stopping this asynctask somehow?


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


Well ill try to be faster:

  • You must be responsible to stop an asynctask if not doing influence negatively your program . Read this.

  • Your asynctask would pass its life doing onPreExecute()-doInBackground(Params...)-onPostExecute(Result)-End of asynctask life

  • Asynctask have been done to execute only one time , then if you wanna execute it another time you must create another one


  1. Yes, the AsyncTask will continue to run if you didn't stop it upon navigation to another Activity. It will continue to run even if the device's configuration changes (e.g. it rotates). If you want to do something on postExecute() that has an effect on the UI, then you have to make sure, that the references of the UI widgets that you modify in this method are valid, even after rotation, when the Activity's recreated.

  2. Yes, you're responsible to stop (that means, .cancel()) you AsyncTask if you don't need it. Note however, that an AsyncTask that is in the middle of its execution will not stop only because you called .cancel() on it. It will continue to run, but its postExecute() method will not be called when the task is completed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜