2

An issue has appeared a few days ago. I have an application that listen for GPS location. The listener is a background service that works all the time, this service saves data in application level and each activity reads this data. So, when i press back button i am able to catch this event and i can stop the service, but when i press HOME button the service is still working although the application is in background mode and this consumes battery, because the GPS always works. How can i handle this event? I do want to stop all services when the user presses HOME button and start them again when user gets back. 10x

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Plamen Nikolov
  • 4,177
  • 3
  • 23
  • 24
  • Its a very old question and seems unanswered. Just trying to give my best solution: I understand problem is not handling home button, rather get the event of application going in background. Android give handle for events like background and foreground of application and I suggest you to use this to disable and enable your service respectively. I hope this helps :) – saurabh Sep 16 '16 at 08:16

6 Answers6

4

It sounds like you're catching the back button either via an onKey... method or in onStop. You should place your code in the onPause() method to ensure it's used whenever the app gets backgrounded.

Al Sutton
  • 3,904
  • 1
  • 22
  • 17
  • Likewise, you will have to (re-)start those services in `onResume()`. – Gubbel Feb 17 '11 at 11:08
  • I can't put my code in onPause() method, because when i start a new activity, the old one will stop the service. And what happens if the new activity needs GPS information too? – Plamen Nikolov Feb 17 '11 at 11:11
  • 2
    The new one could restart it. It's the same logic as when you press the back button and the user goes to a previous activity which needed the service. – Al Sutton Feb 17 '11 at 11:17
4

You can not handle home button events in your Android application. Google has made it for internal use only.

LINK 1 LINK 2

UMAR-MOBITSOLUTIONS
  • 77,236
  • 95
  • 209
  • 278
2
   @Override
    protected void onUserLeaveHint() 
   { 
        // When user presses home page
        Log.v(TAG, "Home Button Pressed");
        super.onUserLeaveHint();
    }
Hamid
  • 355
  • 3
  • 10
0

create a custom activity called customActivity extends Activity now override method(in customActivity) to catch home button event and stop your service(create & start service in application class). Now extends customActivity instead of Activity for any activity_class.

shantanu
  • 9
  • 1
0

You could create a OnKeyListener, and check if the pressed key was Home. I never tried it, though.

gnclmorais
  • 4,897
  • 5
  • 30
  • 41
-5

Long press the HOME button, it will enlist the running process, select the one you want and then exit it gracefully.

OR From Home -> settings -> application -> manage application you can kill the unwanted process.

SHW
  • 145
  • 1
  • 10