2

I've been looking around at many forum discussions, but none of them answers properly how to handle runtime changes that forces the actual activity to restart.

In my case, for example, my activity uses an AsyncTask to show a ProgressBar while fetching data from server. But, if user just rotates the screen, the activity is restarted and repeats the request to server.

If screen rotation is done while the AsyncTask is still in doInBackground(), waiting for server's response, I get a android.view.WindowLeaked error.

I just want to, whenever the screen gets rotated or another interruption occurs, my activity continues doing its job from where it stopped, could that be this hard?

onSaveInsanceState() is recommended? How could I save a partially received JSON in a Bundle? Or maybe I should use onRetainNonConfigurationInstance()...

Will send a bottle of Brazilian's drink "caipirinha" for the good soul that helps me...

Lucas Jota
  • 1,863
  • 4
  • 24
  • 43

1 Answers1

0

You need to use a different architecture.

Move the background operation from the AsyncTask into a Service. A service runs in the background independent of any Activity, and does not get restarted when you change the orientation of the device.

The background Service can communicate with the foreground Activity via broadcasts. Within the service, you can send broadcasts w/ progress info using sendBroadcast(). You can receive the broadcasts in the Activity using a BroadcastReceiver.

EDIT: For less drastic approaches that may be suitable depending on your situation, see: http://developer.android.com/guide/topics/resources/runtime-changes.html. In particular, if you do not use different resources for landscape and portrait, then the second method (handling the configuration change yourself) may work well.

EDIT2: Some additional info here: Activity restart on rotation Android

Community
  • 1
  • 1
Theo
  • 5,963
  • 3
  • 38
  • 56
  • Thanks, it seems using services is a nice approach. For now I'm working in another issue, but will give you feedback as long as I can. – Lucas Jota Jun 25 '12 at 13:23
  • I will try using started services, because they look easyer to implement. But it's not clear to me if bound services are or not more appropriate. – Lucas Jota Jul 02 '12 at 18:42
  • 1
    Agreed, started services are better in this situation. Bound services are more complex and have some issues such as memory leaks on some versions of Android. – Theo Jul 02 '12 at 18:48