一、重写方法,处理对应的按键回调事件
当处理物理按钮事件的时候提供的回调方法有
- onKeyDown()
- onKeyUp()
- onKeyLongPress()
如下是例子:返回键被按下,提示退出程序
public class MainActivity extends Activity {
private long exitTime = 0; //退出时间变量值
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
exit();
return true; //拦截返回键
}
return super.onKeyDown(keyCode, event);
}
public void exit() {
if ((System.currentTimeMillis() - exitTime) > 2000) { //计算按键时间差是否大于两秒
Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else {
finish();
System.exit(0); //销毁强制退出
}
}
}
二、键值
按键名 | 中文名 | code |
---|---|---|
KEYCODE_POWER | 电源键 | 26 |
KEYCODE_HOME | HOME键 | 3 |
KEYCODE_BACK | 返回键 | 4 |
KEYCODE_MENU | 菜单键 | 82 |
KEYCODE_CAMERA | 拍照键 | 27 |
KEYCODE_VOLUME_UP | 音量增加键 | 24 |
KEYCODE_VOLUME_DOWN | 音量减少键 | 25 |
KEYCODE_VOLUME_MUTE | 扬声器静音键 | 164 |
KEYCODE_CALL | 拨号键 | 5 |
KEYCODE_ENDCALL | 挂机键 | 6 |
三、framework按键消息派发
按键消息派发(android 4.2(jb5))
frameworks/base/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
dispatchUnhandledKey
interceptFallback
interceptKeyBeforeQueueing [interceptKeyTq]
interceptKeyBeforeDispatching [interceptKeyTi]
四、增加一个按键
底层抓键值:adb shell getevent /dev/input/event0
adb shell getevent /dev/input/event1
0001 012c 00000001 : 十六进制,012c=300
先用adb shell getevent,可以看到选项,后面的是可以选的
增加一个按键([android 5.1,6.0])
alps/device/xxx/xxx/mtk-kpd.kl
key 300 FM
alps/frameworks/native/include/android/keycodes.h
AKEYCODE_FM = 300,//added for fm
alps/frameworks/native/include/input/InputEventLabels.h
static const InputEventLabel KEYCODES[] = {
// added for fm
DEFINE_KEYCODE(FM), //= {"FM",AKEYCODE_FM}
}
//注:宏定义函数#define DEFINE_KEYCODE(key) { #key, AKEYCODE_##key } = {"key", AKEYCODE_key}
//#是把宏参数变为一个字符串,##是把两个宏参数连接在一起
alps/frameworks/base/core/java/android/view/KeyEvent.java
/**
* @hide
*/
public static final int KEYCODE_FM = 300;
//added for fm
private static final int LAST_KEYCODE = KEYCODE_FM;//modify for fm