Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: application global onPause() and onResume()?

Is there something like an application global onPause() and onResume()?

My main activity listens for GPS fixes, which I want to continue working when switching to another screen/activity. Therefor I cannot unregister my LocationListener in the activity's onPause(). However I still want to unregister my GPS listener when switching to another application (so save battery) and turning it back on when returning to my application, regardless what screen/activity the user is currently in.

Any ideas?

like image 323
znq Avatar asked Jan 14 '10 12:01

znq


1 Answers

Is there something like an application global onPause() and onResume()?

No, sorry.

My main activity listens for GPS fixes, which I want to continue working when switching to another screen/activity. Therefor I cannot unregister my LocationListener in the activity's onPause(). However I still want to unregister my GPS listener when switching to another application (so save battery) and turning it back on when returning to my application, regardless what screen/activity the user is currently in.

Here's one possible approach:

Step #1: Move the LocationListener logic into a Service, which the activities connect to via the local binding pattern or something. Also have at least one service call startService(), so an unbindService() won't cause the Service to go away (assuming you're using the local binding pattern).

Step #2: Have the activities call into the service during onPause() and onResume().

Step #3: Have the service maintain a reference count of outstanding activities.

Step #4: When the reference count reaches zero, have the service arrange to get woken up via a Timer and TimerTask. Also, cancel any such outstanding TimerTask if the reference count gets incremented.

Step #5: Have the TimerTask shut down GPS if it ever gets executed.

The net is that you will only release GPS after such-and-so amount of inactivity. That inactivity could be for any reason.

like image 93
CommonsWare Avatar answered Oct 14 '22 17:10

CommonsWare