How to persist state in Android onPause using android HttpRequest

My understanding of the Android lifecycle model is that when called, onPause()

I have to save any state that needs to be saved, because my application could be terminated at any time after I return. I targeted Gingerbread so onStop

it can never be called.

However, in my application, some state is kept on the remote server. I periodically clear this state, but if onPause is called, I'm not sure if this is correct because I understand that as soon as onPause returns, my application might be killed. Since I have to run the android HTTP request on a different thread, this seems to be problematic: if I run the request in onPause then return, then my app might be killed before the remote request retains state by exiting (or even starting!).

I think I need to put some kind of sync where I go to sleep and wait for the request to work, but at first I'm not sure if I can even do it in onPause, and secondly, onPause shouldn't do very long. to complete, so if there is network latency it can cause problems as well.

Is there a recommended way to persist state in onPause when the state needs to be cleaned up on a remote server, or in general by some method that requires a separate thread?

+3


source to share


2 answers


Recommended way to persist state in onPause when state needs to be flushed to remote server:



in OnPause start the service (Android service) and clear your state from the server from that service and close the service after the required task is completed.

+2


source


Not really sure what you are doing, but

You can put your HttpRequest on a Service when you create a Thread from this here, it won't get killed when your activity hits Pause.



Then you can call back to your application using BroadcastReciever and this will fire up your asset if it is not already running.

+2


source







All Articles