SimonH SimonH - 1 year ago 65
Android Question

How to receive and process location changes when an Activity is paused

I am looking for a bit of app design advice.

I have an app that connects to the Google Location Services and tracks location coordinates it receives. These are displayed as a path on the UI.

When the screen times out and goes blank then this

will, of course, shut down as per the normal Activity life cycle.

However - I atill want to record the co-ordinates coming back in each
event from Location Services, but, of course, the
has paused so it cannot do that.

I don't particularly want to prevent the screen from blanking in the Manifest (and thus the
would never pause). Though I believe it would still pause if, say, a phone call is received etc.

My solution would be to start an
in one of the
pausing events (either
) to receive Location updates, and then when the
restarts, collect the data from the Service and close the Service down.

Would this be an efficient and correct way of achieving this, or is there some Android black art that I don't know about? If so, is
the correct way to go about it (or should I use

Answer Source

In order to tie up loose ends, I'll add my own answer to this now I have implemented something.

My solution in the end was not an IntentService. This was because I thought that the IntentService would consider its work to be the actual setting up of the LocationService and once that work had been completed then it would shut itself down rather than hang about waiting for LocationService 'pings'.

Therefore, I implemented a normal Service, but I bound it to the calling Activity. I also set up a callback to the Activity. This way when a 'ping' was received I could process it and pass back the data directly to the Activity. Also, the Service would remain alive as long as the binding was in place. I clear the binder when the Activity is destroyed.

This worked perfectly....HOWEVER

I then discovered that the reason that the LocationService 'pings' were not being handled in the Activity was bacause I was disconnecting the GoogleAPIClient when the Activity onStop was called. Having removed this, the Activity processed the 'pings'even in its stopped state, so no Service was required anyway.

Therefore the correct answer to this question is... Activity should continue processing in the background (unless it's destroyed for memory management purposes), so check you're not stopping stuff in your 'shutdown' handlers onPause onStop etc. Then you won't waste time writing services like I did!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download