一、篇头
最近实现热键想功能,简单总结了下全志平台Android 11 的响应全局热键的方法。
二、需求
实现全局热键,响应F-、AF、F+三个按键,AF只用于启动调焦界面,F-和F+除了可以启动调焦界面外,还用于调整镜头的焦距(控制步进电机进退)。
三、按键配置
配置方法略,可参考本人红外或蓝牙的按键配置的相文章。
- 如下在kl文件中添加3个按键
- ZOOM_IN和ZOOM_OUT用于控制调焦电机的进和退,也用于启动调焦界面
- APP_SWITCH 暂用于启动调焦界面
key 53 ZOOM_IN //对应遥控器的F-
key 52 ZOOM_OUT //对应遥控器的F+
key 64 APP_SWITCH //对应遥控器的AF
四、代码实现
4.1 全局按键响应:TvWindowManager.java
- 位置:android\frameworks\base\services\core\java\com\android\server\policy\TvWindowManager.java
@Override
public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags) {
int keyCode = event.getKeyCode();
final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
Log.d(TAG,"key event key = " + KeyEvent.keyCodeToString(keyCode));
…… 略……
if (down) {
…… 略……
case KeyEvent.KEYCODE_APP_SWITCH:
case KeyEvent.KEYCODE_ZOOM_IN:
case KeyEvent.KEYCODE_ZOOM_OUT:
//(1)判断当前topActivity,如果已经打开了调焦界面,则不再启动
if (mActivityManager == null)
mActivityManager = (ActivityManager)mContext.getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn = mActivityManager.getRunningTasks(1).get(0).topActivity;
String ActivityName = cn.getClassName();
Log.d(TAG, "current activity is " + ActivityName);
if (ActivityName.contains("cictech.projector.FocusActivity")) {
Log.d(TAG, " do NOT start FocusActivity ");
break;
}
//(2)启动调焦界面
Log.d(TAG, " Key down to start FocusActivity ");
Intent focusIntent = new Intent();
focusIntent.setComponent(new ComponentName("com.android.tv.settings", "com.android.tv.settings.szhou.projector.FocusActivity"));
focusIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
focusIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(focusIntent);
break;
4.2 调焦界面:FocusActivity.java
public class FocusActivity extends Activity {
private final String TAG = "FocusActivity";
private JniMotor mJniMotor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_focus);
mJniMotor = new JniMotor();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode){
case KeyEvent.KEYCODE_ZOOM_IN:
{
//right
Log.d(TAG, "KEYCODE_ZOOM_IN + 5" + mJniMotor.ioctl(1, 5));
}
break;
case KeyEvent.KEYCODE_ZOOM_OUT:
{
//left
Log.d(TAG, "KEYCODE_ZOOM_OUT -5 " + mJniMotor.ioctl(2, 5));
}
break;
default:
return super.onKeyDown(keyCode, event);
}
return true;
}
}
4.3 调试打印
- Andorid 打印如下