1

I know that I cant override the home button like with the back button. But can the android system fire an event if the home button is pressed? I want to catch this action in order to show a warning message if the user presses the home button. I've looked into several options, the most obvious one, for beginner would be to override the home button

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_HOME) {
        // action goes here
    } else {
        return super.onKeyDown(keyCode, event);
    }
}

But this doesnt work, and I'm completly aware of it.

The onPause method will be called once the current Activity finishes. This method will also be called when the user changes Activity in my application. So is there anyway I can show the user a notifying box, when he presses the home button?

Thanks in advance

Tobias Moe Thorstensen
  • 8,861
  • 16
  • 75
  • 143

2 Answers2

2

Actually, it is not possible to catch home button pressed event like others, it is a feature to protect the user.

But there is a hack for your situation:

@Override
public void onAttachedToWindow()
{  
    this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);     
    super.onAttachedToWindow();  
}

onAttachedToWindow

This is called when the view is attached to a window

You may read Activity Lifecycle how this hack works.

Also, here is the evidence which shows this method works.

Community
  • 1
  • 1
Samet Atdag
  • 982
  • 6
  • 21
2
@Override
    protected void onUserLeaveHint() {
        // TODO Auto-generated method stub
        super.onUserLeaveHint();
    }

This can also help

Dinesh Prajapati
  • 9,274
  • 5
  • 30
  • 47