Domanda

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.

È stato utile?

Soluzione

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

Altri suggerimenti

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);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top