安卓开发最简单的按键监听事件

时间:2022-08-29 22:44:59

部分代码

private static final String TAG = "MainActivity";
private boolean lockLongPressKey, isLongPressKey;//是否长按
 @Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {

case 270:
Log.e("000000000000000000", "00000000000000000");
ScanService.openScan();
return true;


case 131:
if (event.getRepeatCount() == 0) {
event.startTracking();
isLongPressKey = false;
} else {
isLongPressKey = true;
}
return true;
case 132:
if (event.getRepeatCount() == 0) {
event.startTracking();
isLongPressKey = false;
} else {
isLongPressKey = true;
}
return true;
}

return super.onKeyDown(keyCode, event);
}

@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
switch (keyCode) {
case 131:
Log.e("F1", "报警啦");
lockLongPressKey = true;
Intent intent = new Intent();
intent.setAction(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + "123456789"));
startActivity(intent);
return true;
case 132:
Log.e("F2", "举报啦");
lockLongPressKey = true;
lockLongPressKey = true;
Intent intent1 = new Intent();
intent1.setAction(Intent.ACTION_CALL);
intent1.setData(Uri.parse("tel:" + "123456789"));
startActivity(intent1);
return true;
}

return super.onKeyLongPress(keyCode, event);
}

public boolean onKeyUp(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
Log.d(TAG, "---->> onKeyDown():keyCode=" + keyCode);
switch (keyCode) {
case 131:
if (lockLongPressKey) {
lockLongPressKey = false;
return true;
}
case 132:
if (lockLongPressKey) {
lockLongPressKey = false;
return true;
}
}
return super.onKeyUp(keyCode, event);
}

@Override
protected void onDestroy() {
// this.unregisterReceiver(scanBroadcastReceiver);
super.onDestroy();
}

代码地址:http://pan.baidu.com/s/1skQWRPN

转载请注明出处,谢谢