一、首先谈一下HOME键(主页键),因为HOME键比较特殊,根据系统的不同处理,来处理的,以下是我常用的方式
1、系统广播方式
private HomeKeyBroadcastReceiver mHomeKeyBroadcastReceiver;
//注册监听hone键广播
if (mHomeKeyBroadcastReceiver == null) {
mHomeKeyBroadcastReceiver = new HomeKeyBroadcastReceiver();
registerReceiver(mHomeKeyBroadcastReceiver, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
}
//注销监听hone键广播。防止内存泄漏
if (mHomeKeyBroadcastReceiver != null) {
unregisterReceiver(mHomeKeyBroadcastReceiver);
mHomeKeyBroadcastReceiver = null;
}
class HomeKeyBroadcastReceiver extends BroadcastReceiver {
private final String SYSTEM_REASON = "reason";
private final String SYSTEM_HOME_KEY = "homekey";// home key
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(intent.getAction())) {
String reason = intent.getStringExtra(SYSTEM_REASON);
if (TextUtils.equals(reason, SYSTEM_HOME_KEY)) {
//做相应的逻辑,比如退出应用,杀死进程
}
}
}
}
}
2、onkey事件来监听,可以用onkeydown,也可以用dispatchKeyEvent,一个道理,这里写dispatchKeyEvent方法的使用
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP) {
if (event.getKeyCode() == KeyEvent.KEYCODE_HOME) {
//做相应的逻辑,比如退出应用,杀死进程
}
}}
这里用ACTION_UP和ACTION_DOWN,都可以,不过还是要看使用场景是怎么样的
其他按键,其实有两种方式,一种是onkey事件,一种是dispatchKeyEvent,最开始接触的同学,可能都会先用onkey事件,比如onKeyDown和onKeyUp,不过Android TV开发时间久了,
dispatchKeyEvent事件也得知道,因为是根据一些特别的情况,例如要通过接口回调,来进行按键事件的传递,举个例子,可能写了一个工具类,专门用来做些事件的处理,这个时候,你要是用onKeyDown,就比较费事,还不如直接传递
KeyEvent,直接按下和抬起的事件都传递了,节省代码行数,下面我写一个简单的用法示例
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
try {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_DOWN) {
//下键
return true;
} else if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_UP) {
//上键
return true;
} else if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_LEFT) {
//左键
return true;
} else if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_RIGHT) {
//右键
return true;
} else if (event.getKeyCode() == KeyEvent.KEYCODE_BACK || event.getKeyCode() == KeyEvent.KEYCODE_ESCAPE) {
//返回键,不同设备键值可能不一样,最好兼容
return true;
} else if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER || event.getKeyCode() == KeyEvent.KEYCODE_DPAD_CENTER) {
//确认键,不同设备键值可能不一样,最好兼容
return true;
} else if (event.getKeyCode() == KeyEvent.KEYCODE_MENU) {
//菜单键
return true;
}
}
//ACTION_UP同理
} catch (Exception e) {
Log.e(TAG, "dispatchKeyEvent:Exception:" + e.toString());
}
return super.dispatchKeyEvent(event);
}