0

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.

grant1842
  • 357
  • 1
  • 7
  • 23
  • This is not possible. There is a very complicated work around which is not worth it. – Hoan Nguyen Mar 13 '13 at 00:25
  • If you're referring to the time based one, then I agree it's not a real solution. This really seems to be a huge problem with android. I understand not being able to trap the event, but we should at least be able to see if it was fired. – grant1842 Mar 13 '13 at 00:29
  • No it is not time base but you have to override a bunch of methods then you can deduct from these that a HOME KEY is pressed. But then you cannot post a script unless you use a service. – Hoan Nguyen Mar 13 '13 at 00:49

2 Answers2

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
    }
}
Hoan Nguyen
  • 18,033
  • 3
  • 50
  • 54
-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);
}
Community
  • 1
  • 1
cloudgroup
  • 67
  • 1
  • 2
  • 2
    public static final int KEYCODE_HOME Added in API level 1 Key code constant: Home key. This key is handled by the framework and is never delivered to applications. Constant Value: 3 (0x00000003) – grant1842 Mar 13 '13 at 00:17