Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When the app goes to background during an AsyncTask execution what should it do?

I have an application that uses AsyncTasks to make calls to a REST server.

Imagine that during a loading period (this is, the AsyncTask going to the REST server and gets data to the next screen) the user presses Home.

What is recommended:

  • Cancel the current AsyncTask(s) and restart when resuming the Activity

or

  • Continue the AsyncTasks but avoiding the startActivity by checking if the app is on background (to avoid the foreground of the new activity after sending the app to background). And onResume sending to the next activity

Worst case scenarios that you should foresee:

  1. The app goes to background and is killed due to lack of memory
  2. The asynctask fails due to timeout or other REST error

After both, the user goes back to the app...

like image 298
neteinstein Avatar asked Jan 11 '12 11:01

neteinstein


2 Answers

Well I ll recommend Service which should use AsyncTask to do its work. Service will insulate your activity from orientation change or user exiting. AsycnTask will insulate from the UI thread being blocked. But do make sure to exit Service when you are done with REST api.

This will give you best of both. Also if you are not using DB as a local cache then you can try that too. So even if the user goes away, the service will store the fetched data in the DB and when the user comes back you can quickly display the screen.

EDIT: Just want to add IntentService are easy to implement.

Try Design Patterns for REST clients on Android by Google for more exhaustive explanation

like image 83
havexz Avatar answered Oct 12 '22 00:10

havexz


Using AsyncTasks can get really messy during a configuration change. From personal experience I would recommend going down the IntentService/ResultReceiver route instead.

See this post for more info:

Restful API service

like image 23
SeanPONeil Avatar answered Oct 12 '22 00:10

SeanPONeil