Android - See if home key is pressed

前端 未结 2 1153
夕颜
夕颜 2021-01-27 09:27

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 activi

相关标签:
2条回答
  • 2021-01-27 10:16

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

    boolean mKeyPress;  
    boolean mUserLeaveHint;
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        mKeyPress = true;
        return super.onKeyDown(keyCode, event);
    } 
    
    @Override
    protected void onUserLeaveHint()
    {
        super.onUserLeaveHint();
        mUserLeaveHint = true;
    }
    
    @Override
    protected void onPause()
    {
        super.onPause();
        if (!mKeyPress && mUserLeaveHint)
        {
            // HOME_KEY is pressed
        }
    }
    
    0 讨论(0)
  • 2021-01-27 10:16

    Looks like a duplicate of this one

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

    @Override
    public boolean dispatchKeyEvent(KeyEvent keyevent) {
    
        if (keyevent.getKeyCode() == KeyEvent.KEYCODE_HOME) {
            //Do here what you want
            return true;
        }
        else
            return super.dispatchKeyEvent(event);
    }
    
    0 讨论(0)
提交回复
热议问题