I have this method in one of my Android Activities:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode == KeyEvent.KEYCODE_BACK)
{
Log.d("Test", "Back button pressed!");
}
else if(keyCode == KeyEvent.KEYCODE_HOME)
{
Log.d("Test", "Home button pressed!");
}
return super.onKeyDown(keyCode, event);
}
But, even though the KEYCODE_HOME is valid, the log method never fires. This works for the back button though. Does anyone know why this is and how to get this to work?
The HOME button cannot be intercepted by applications. This is a by-design behavior in Android. The reason is to prevent malicious apps from gaining control over your phone (If the user cannot press back or home, he might never be able to exit the app). The Home button is considered the user's "safe zone" and will always launch the user's configured home app.
The only exception to the above is any app configured as home replacement. Which means it has the following declared in its AndroidManifest.xml for the relevant activity:
When pressing the home button, the current home app's activity's
onNewIntent
will be called.I also struggled with HOME button for awhile. I wanted to stop/skip a background service (which polls location) when user clicks HOME button.
here is what I implemented as "hack-like" solution;
on each activity
and the background service checks the appstate in each loop, skips the action
it works well for me, at least not draining the battery anymore, hope this helps....
I have a simple solution on handling home button press. Here is my code, it can be useful:
As a summary, put a boolean in the activity, when activity switch occurs(startactivity event), set the variable and in onpause event check this variable..
use
onPause()
method to do what you want to do on home button.KeyEvent.KEYCODE_HOME
can NOT be intercepted.It would be quite bad if it would be possible.
(Edit): I just see Nicks answer, which is perfectly complete ;)
I found that when I press the button HOME the onStop() method is called.You can use the following piece of code to monitor it: