How to handle KeyEvent of home button in an Android application?

Hasmukh picture Hasmukh · Oct 11, 2011 · Viewed 7.6k times · Source

I'm developing an application in Android, and I use the the following code to handle the KeyEvent for the back button:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK)) 
    {           
        finish();
    }

    return super.onKeyDown(keyCode, event);
}

How would I go about doing this for the home button?

Answer

Vineet Shukla picture Vineet Shukla · Oct 11, 2011

You can not control the behaviour of Home key. You will not get the event of Home key but you can disable it but it is highly recommended you should not do this.Before blocking the Home key refer this post.

However you can block the home key like this:

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