如何在Android应用程序中处理home按钮的KeyEvent?

发布于 2024-12-09 04:39:53 字数 303 浏览 0 评论 0原文

我正在 Android 中开发一个应用程序,并使用以下代码来处理后退按钮的 KeyEvent:

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

    return super.onKeyDown(keyCode, event);
}

我将如何为主页按钮执行此操作?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

噩梦成真你也成魔 2024-12-16 04:39:53

您无法控制 Home 键的行为。您不会收到 Home 键的事件,但您可以禁用它,但强烈建议您不要这样做。在阻止 Home 键之前,请参阅此 帖子

但是您可以像这样阻止 home 键:

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

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();
}
筱果果 2024-12-16 04:39:53

正如这个问题所暗示的:Android Overriding home key 不幸的是这是不可能的。也许还有其他方法来实现您想要的行为?

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

浅唱ヾ落雨殇 2024-12-16 04:39:53

明显的答案是 - 在您的活动的 onPause() 方法中处理主页键按下。当用户按下 home 键时调用此回调。有保证。 Home 键不适合你,但是
对于操作系统和用户。

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.

ゞ记忆︶ㄣ 2024-12-16 04:39:53

阅读这些:

覆盖主页按钮 -我该如何摆脱选择?

Android - 如何捕获按下主页按钮?

主页按钮应该只做一件事,而且只能持续做一件事。让用户返回主屏幕。即使您可以覆盖它的行为,这也是一件对用户极其不友好的事情。 所以不要这样做,并以不同的方式解决你的问题!强文字

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文