Skip to content Skip to sidebar Skip to footer

Android - See If Home Key Is Pressed

I'm making a game and if the activity is left in any way by the user (back or home key pressed), the activity needs to end the game by posting to a script and ending the activity.

Solution 1:

Ok here is the work around if you insist. Android next version may just close the loophole.

boolean mKeyPress;  
boolean mUserLeaveHint;

@OverridepublicbooleanonKeyDown(int keyCode, KeyEvent event)
{
    mKeyPress = true;
    returnsuper.onKeyDown(keyCode, event);
} 

@OverrideprotectedvoidonUserLeaveHint()
{
    super.onUserLeaveHint();
    mUserLeaveHint = true;
}

@OverrideprotectedvoidonPause()
{
    super.onPause();
    if (!mKeyPress && mUserLeaveHint)
    {
        // HOME_KEY is pressed
    }
}

Solution 2:

Looks like a duplicate of this one

Android, How to receive home button click through broadcast receiver?

@OverridepublicbooleandispatchKeyEvent(KeyEvent keyevent) {

    if (keyevent.getKeyCode() == KeyEvent.KEYCODE_HOME) {
        //Do here what you wantreturntrue;
    }
    elsereturnsuper.dispatchKeyEvent(event);
}

Post a Comment for "Android - See If Home Key Is Pressed"