android模拟键盘事件
网上的搜出来的错误答案:
网上抄来抄去的方法,
IWindowManager 类已经不可以使用了,不知道现在转贴的朋友是否自己测试?
// static public void sendVKeyDelay(int key) {
// final int keyCode = key;
// Thread sendKeyDelay = new Thread(){
// public void run() {
// try {
// Thread.sleep(100);
//
// long now = SystemClock.uptimeMillis();
// KeyEvent keyDown = new KeyEvent(now, now, KeyEvent.ACTION_DOWN,
// keyCode, 0);
// IWindowManager wm = IWindowManager.Stub.asInte易做图ce(
// ServiceManager.getService("window"));
// wm.injectKeyEvent(keyDown, false);
//
// KeyEvent keyUp = new KeyEvent(now, now, KeyEvent.ACTION_UP,
// keyCode, 0);
// wm.injectKeyEvent(keyUp, false);
// } catch (InterruptedException e) {
// e.printStackTrace();
// } catch (RemoteException e) {
// e.printStackTrace();
// }
// }
// };
// sendKeyDelay.start();
// }
=======================================
正确的方法:
调用:simulateKey(KeyEvent.KEYCODE_BACK);
public static void simulateKey(final int KeyCode) {
new Thread () {
public void run () {
try {
Instrumentation inst=new Instrumentation();
inst.sendKeyDownUpSync(KeyCode);
} catch(Exception e) {
Log.e("Exception when sendKeyDownUpSync", e.toString());
}
}
}.start();
}
摘自 韩鹏程的专栏
补充:移动开发 , Android ,