简体   繁体   中英

How to handle KeyEvent of home button in an Android application?

I'm developing an application in Android, and I use the the following code to handle the KeyEvent for the back button:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK)) 
    {           
        finish();
    }

    return super.onKeyDown(keyCode, event);
}

How would I go about doing this for the home button?

As this question suggests: Android Overriding home key this is unfortunately not possible. Perhaps there is some other way to implement your desired behavior?

You can not control the behaviour of Home key. You will not get the event of Home key but you can disable it but it is highly recommended you should not do this.Before blocking the Home key refer this post .

However you can block the home key like this:

@Override
public void onAttachedToWindow() {
    this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
    super.onAttachedToWindow();
}

Obvious answer is - handle home key press in onPause() method of your activity. This callback is called when user hits home key. Guaranted. Home key is not for you, but for OS and user.

Read these :

Overriding the Home button - how do I get rid of the choice?

Android - How to catch that the Home button was pressed?

The home button is supposed to do one thing and one thing only and consistently. Get the user back to the the HOME screen. Even if you could override it's behavior it would be an extremely user-unfriendly thing to do. So don't do it and solve your problem differently!strong text

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM