Search code examples
androidandroid-activityhalt

My android app should suspend activity when not on screen


An android app that I'm writing seems to consume a lot of battery even when it's not the foreground application. My assumption is that I need to unregister the listeners for gps, orientation, etc., when the application is not in the foreground.

The thing is, I have a variety of different activities that I switch between and I don't want the listeners to be unregistered as long as I'm switching between them. However, if the user holds down home and switches to another app (or if a phonecall happens or whatever) I want my app to stop doing anything at all.

All the on* methods of an activity are specific to that activity. How do I listen for switching away from my application entirely?


Solution

  • My assumption is that I need to unregister the listeners for gps, orientation, etc., when the application is not in the foreground.

    Correct.

    The thing is, I have a variety of different activities that I switch between and I don't want the listeners to be unregistered as long as I'm switching between them.

    Sure you do. Each activity must stand alone, not making any assumptions about any other activity that is (or is not) around. You are welcome to move this stuff to a service, bound to by each of your activities, if you prefer.

    How do I listen for switching away from my application entirely?

    There is no such concept in Android.