简体   繁体   中英

Android: How to handle that the application is minimized by HOME button

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

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.

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

LINK 1 LINK 2

   @Override
    protected void onUserLeaveHint() 
   { 
        // When user presses home page
        Log.v(TAG, "Home Button Pressed");
        super.onUserLeaveHint();
    }

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM