Android 模拟按键功能实现
开发中遇到一个按键,需要发送两个键值,一帮情况下,只能一个按键只能发送一个键值,那两个键值怎么实现呢?其实就是一个api调用的事情,android都有现成的我们直接拿来用就可以了!
代码如下
services/core/java/com/android/server/policy/PhoneWindowManager.java 下
/* 模拟音量+键操作 */
private final Runnable mKeyCodeVolumeUpHandler = new Runnable() {
@Override
public void run() {
if (DEBUG_KEYGUARD) Slog.d(TAG, "mKeyCodeVolumeUpHandler run,send code KEYCODE_VOLUME_UP" );
new Instrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_VOLUME_UP);
autoSpinBtnChangeChannelDefaultMode.removeMessages(null);
autoSpinBtnChangeChannelDefaultMode.sendMessageDelayed(Message.obtain(),3*1000);
}
};
/* 模拟音量-操作 */
private final Runnable mKeyCodeVolumeDownHandler = new Runnable() {
@Override
public void run() {
if (DEBUG_KEYGUARD) Slog.d(TAG, "mKeyCodeVolumeUpHandler run,send code KEYCODE_VOLUME_DOWN" );
new Instrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_VOLUME_DOWN);
autoSpinBtnChangeChannelDefaultMode.removeMessages(null);
autoSpinBtnChangeChannelDefaultMode.sendMessageDelayed(Message.obtain(),3*1000);
}
};
// TODO(b/117479243): handle it in InputPolicy
/** {@inheritDoc} */
@Override
public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags) {
final int keyCode = event.getKeyCode();
final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
boolean isWakeKey = (policyFlags & WindowManagerPolicy.FLAG_WAKE) != 0
|| event.isWakeKey();
if (CHANNEL_UP_KEY == event.getKeyCode()) {
//
mHandler.post(mKeyCodeVolumeUpHandler);
if (DEBUG_KEYGUARD) Slog.d(TAG, "CHANNEL_UP_KEY to click, simulate to volume up action");
}else if (CHANNEL_DOWN_KEY == event.getKeyCode()) {
if (DEBUG_KEYGUARD) Slog.d(TAG, "CHANNEL_DOWN_KEY to click, simulate to volume down action");
mHandler.post(mKeyCodeVolumeDownHandler);
}
}
以上代码中,在interceptKeyBeforeQueueing 方法中,拦截指定键值,然后调用发送一个handler的任务,然后在runnable中实现模拟按键就可以了!
参考文章:
Instrumentation中的sendKeyDownUpSync的调用过程