android-自定义处理输入事件

在一个继承了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以上已不可用

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值