Lior Ohana
Lior Ohana

Reputation: 3527

Android: Handling GPS from multiple activities

I'm working on an Android app that uses the GPS from multiple activities. I was looking for a good way to access the GPS from all activities without start/stopping the GPS (receiving events) each time I move from one activity to the other. In this link it is recommended to use a service and bind/unbind on OnStart/OnStop since they overlap.

I really like the idea however, I've left with one problem. I'd the like to stop the GPS when my app is no longer active (i.e, home button was pressed). In this case, only the OnPause will be called.

Any ideas?

Thanks.

Upvotes: 0

Views: 817

Answers (2)

NickT
NickT

Reputation: 23873

I've used this approach, it works fine if you unbind in onStop(). That method will be called when your application is no longer visible. Pressing the home key will make your application invisible.

Log when I go from select activity to OSM activity, to Google map activity, then hit home button. (OSM and Google both use the service with the GPS location listener) (I paused the OSM activity to change a preference setting, hence the pause and restart)

04-15 17:41:47.903: D/ACTIVITY(376): Select Mode Activity onPause
04-15 17:41:47.953: D/ACTIVITY(376): OSM Activity onCreate
04-15 17:41:48.043: D/ACTIVITY(376): OSM Activity onStart
04-15 17:41:48.063: D/ACTIVITY(376): OSM Activity onResume
04-15 17:41:49.394: D/ACTIVITY(376): Select Mode Activity onStop
04-15 17:42:04.213: D/ACTIVITY(376): OSM Activity onPause
04-15 17:42:04.763: D/ACTIVITY(376): OSM Activity onStop
04-15 17:43:00.483: D/ACTIVITY(376): OSM Activity onStart
04-15 17:43:00.533: D/ACTIVITY(376): OSM Activity onResume
04-15 17:43:20.683: D/ACTIVITY(376): OSM Activity onPause
04-15 17:43:20.723: D/ACTIVITY(376): Google Activity onCreate
04-15 17:43:20.853: D/ACTIVITY(376): Google Activity onStart
04-15 17:43:20.873: D/ACTIVITY(376): Google Activity onResume
04-15 17:43:21.307: D/ACTIVITY(376): OSM Activity onStop
04-15 17:43:40.833: D/ACTIVITY(376): Google Activity onPause
04-15 17:43:41.403: D/ACTIVITY(376): Google Activity onStop

Upvotes: 2

Shankar Agarwal
Shankar Agarwal

Reputation: 34765

When ever we press Home button any other activity come in fore ground a part from activity life cycle method we also have an method that is called onUserLeaveHint method.

onUserLeaveHint() is a protected method as other lifecycle methods of the activity and if you are handling onUserLeaveHint this will take care of the following case

When User hits home key

When User hits back key

When User hits annunciator bar

Basically it hints about the user is trying to leave your activity. That means if you are handling onUserLeaveHint() you don’t need to handle onBackPressed() in your code.

Upvotes: 0

Related Questions