0

Possible Duplicate:
Home button listener

I use below code to listener home button pressed:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
    System.out.println(keyCode);
    if(keyCode == KeyEvent.KEYCODE_HOME) {
        //do things
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

Why it no response? I try to show the keyCode. While I press other button, it show keycode. Only press home button, it does show. How can I modify it?

Community
  • 1
  • 1
brian
  • 6,802
  • 29
  • 83
  • 124

3 Answers3

6

you can't catch whether the home button was pressed .onKEyDown() doesn't seem to work for HOME Android has kept the functionality of home button separate from other keys. The preferred way is to deal with onStop() of your Activity being called when the user presses HOME.

@Override
protected void onStop() 
{
    super.onStop();
//put your logic here 
}
Akhil
  • 13,888
  • 7
  • 35
  • 39
  • Because I want to reset value while home button pressed, but not reset value if call other activity. Use onStop() it seems not arrive it? – brian Apr 02 '12 at 07:21
  • wherever you have put intents to fire up new activities, put a boolean flag variable next to them. If the intent code has been fired, it will also make the flag tru below it. Then check for that flag in your onStop() – Akhil Apr 02 '12 at 07:25
2

Another option is that on pressing Home Button onStop() is called, you can write your code in that.

@Override
protected void onStop() 
{
    super.onStop();
    Log.d(tag, "Home is called");
    // insert here your instructions
}
Bhavin
  • 6,020
  • 4
  • 24
  • 26
  • Because I want to reset value while home button pressed, but not reset value if call other activity. Use onStop() it seems not arrive it? – brian Apr 02 '12 at 07:18
  • @brian: i am not sure but try to set the Value as final and try further. – Bhavin Apr 02 '12 at 07:22
1

You might have to add this method to your activity,

    @Override
public void onAttachedToWindow() {
    super.onAttachedToWindow();
    this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);           
}
Andro Selva
  • 53,910
  • 52
  • 193
  • 240