From the answers in the stackoverflow I found that Home button can be overriden? But I found an application in the android market called "Mxplayer" where you can lock all buttons while playing video. How are they doing this? Can we override the home button in android?
Asked
Active
Viewed 1.1k times
2 Answers
12
This solution works upto 2.3,
Override the below method in your Activity,
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
}
And now handle the key event like this,
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_HOME)
{
Log.i("Home Button","Clicked");
}
if(keyCode==KeyEvent.KEYCODE_BACK)
{
finish();
}
return false;
};

Andro Selva
- 53,910
- 52
- 193
- 240
-
But this cancels the default behaviour of home button. Even if I use `return super(keyCode, event)` instead of `return false` in `onKeyDown`. – User Sep 13 '12 at 11:06
-
I want to catch home button press to do something tracking-related, but the effect for the user has to be the same. – User Sep 13 '12 at 11:07
-
then try without overriding onKeyDown. Do your stuff in onAttachedWindow() and see if ti works – Andro Selva Sep 13 '12 at 11:11
-
1I get the following error even with "DISABLE_KEYGUARD" permission set. Has 4.1 fixed this security loophole? android.view.WindowManager$BadTokenException: Unable to add window android.view.ViewRootImpl$W@41730348 -- permission denied for this window type – Graeme Oct 24 '12 at 14:40
-
@Graeme i am getting the same for ICS and jelly bean versions, did u get a way of solving this ? – Rat-a-tat-a-tat Ratatouille Oct 28 '13 at 07:17
0
Yes you can. Use the following code:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_HOME)) {
//do nothing
return true;
}
return super.onKeyDown(keyCode, event);
}

Kazekage Gaara
- 14,972
- 14
- 61
- 108