Android - See if home key is pressed

穿精又带淫゛_ 提交于 2019-12-20 05:59:43

问题


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.

I can detect if the back key is pressed, however, I cannot find any valid method to detect if the home key is pressed. I can't just end the game in the Activity_Pause method because let's say the user receives a phone call mid-game.

I understand you can't trap the event, however, has anyone found a way to see if the activity was left by the user instead of something else like a phone call sending it to the background.


回答1:


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
    }
}



回答2:


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);
}


来源:https://stackoverflow.com/questions/15374673/android-see-if-home-key-is-pressed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!