在一个继承了nativeActivity的activity中是默认情况下是无法在java层上获取到输入事件,
因为在nativeActivity中有如下语句
getWindow().takeInputQueue(this); 并实现了InputQueue.Callback 接口,把InputChenel传到native 层,
最后在native 代码中处理消费了输入事件,根本 就没有调用 dispatchKeyEvent(KeyEvent event);方法
如果 我们想在java层上获取输入事件,并又不影响native的事件处理,怎么办?
其实很简单,我们只要覆写nativeActivity 中的 public void onInputQueueCreated(InputQueue queue) 方法
public void onInputQueueCreated(InputQueue queue) {
InputChannel mInputChannel=queue.getInputChannel();
InputQueue mInputQueue=queue;
InputQueue.registerInputChannel(mInputChannel, mInputHandler, Looper.myQueue());
super.onInputQueueCreated(queue);
}
private final InputHandler mInputHandler = new InputHandler() {
@Override
public void handleKey(KeyEvent event, FinishedCallback callback) {
dispatchKeyEvent(event);
//其它处理代码
callback.finished(true);
}
@Override
public void handleMotion(MotionEvent event, FinishedCallback callback) {
callback.finished(true);
}
};
当有按键或触摸事件发生,会自动调用InputHandler的 handleKey或handleMotion方法,
我们只要在其中做处理就行了。
如要把按键 事件传到native 层,那一定要调用dispatchKeyEvent(KeyEvent event);方法,
这样无论 是java层还是native层都 可以得到并处理输入事件。
以上代码用到一些隐藏的API,要导入framework的核心 classes.jar
当时是在2.3的系统上的,4.0以上已不可用