My understanding of the Android lifecycle model is that when onPause() is called I should save any state that needs to be saved, because my app could be terminated at any point after I return. I'm targeting Gingerbread, so onStop might never be called.

However in my app some state is being saved on a remote server. I periodically flush this state but if onPause is called I am not sure the correct thing to do, because my understanding is that as soon as onPause returns my app could be killed. Since I have to run the android http request in another thread this seems problematic: if I start the request in onPause then return, then my app might be killed before the remote request to save the state completes (or even starts!).

I am thinking I should put some sort of synchronization where I go to sleep and wait for the request to work, but first I'm not sure I can even do this in onPause, and second, onPause isn't supposed to take very long to complete so if there is network delay this could cause issues as well.

Is there some recommended way of saving state in onPause when the state needs to be flushed to a remote server or in general by some method that requires a separate thread?

有帮助吗?

解决方案

recommended way of saving state in onPause when the state needs to be flushed to a remote server:

in OnPause start a service(Android Service) and flush your state to server from that service and close the service after the completion of your desired task.

其他提示

Not entirely sure what you are doing, but

You can put your HttpRequest into a Service, when you spawn a Thread from here this will not be killed when your activity hit's onPause.

You can then call back to your app using a BroadcastReciever and this will start your Activity up if it isn't started already.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top