用android捕捉按键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2261914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 05:11:53  来源:igfitidea点击:

Catch keypress with android

androidkeymessagekeypress

提问by shuwo

How can i catch a phone keypress with the android SDK? i've been looking around for hours without finding anything..

如何使用 android SDK 捕捉电话按键?我已经找了几个小时没有找到任何东西..

For example:

例如:

In some cases, i want to catch the message when a user presses the "hang up" button on the phone, and then discard the message before it reaches the OS.

在某些情况下,我想在用户按下电话上的“挂断”按钮时捕捉消息,然后在消息到达操作系统之前将其丢弃。

Is this possible?

这可能吗?

回答by

You can either handle key events from a view or in general for your whole application:

您可以从视图或整个应用程序中处理关键事件:

Handle onKey from a View:

从视图处理 onKey:

public boolean onKey(View v, int keyCode, KeyEvent event) {
    switch (keyCode) {
        case KeyEvent.KEYCODE_ENTER:
         /* This is a sample for handling the Enter button */
      return true;
    }
    return false;
}

Remember to implement OnKeyListener and to set your listener YourView.setOnKeyListener(this);

记得实现 OnKeyListener 并设置你的监听器 YourView.setOnKeyListener(this);

The second possibility would be:

第二种可能是:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
     switch (keyCode) {
     case KeyEvent.KEYCODE_MENU:
        /* Sample for handling the Menu button globally */
        return true;
     }
     return false;
} 

You could also ta a look at onKeyUp.

你也可以看看onKeyUp

Resource: http://developer.android.com/reference/android/view/View.html

资源:http: //developer.android.com/reference/android/view/View.html

And here you can see a list with all KeyEvents

在这里你可以看到一个包含所有KeyEvent的列表