android中模拟按键的另外一种方法
2010-05-31 14:17:00 来源:WEB开发网在com.android.commands.input中发现这一方法
view plaincopy to clipboardprint?
private void sendKeyEvent(String event) {
int eventCode = Integer.parseInt(event);
long now = SystemClock.uptimeMillis();
Log.i("SendKeyEvent", event);
try {
KeyEvent down = new KeyEvent(now, now, KeyEvent.ACTION_DOWN, eventCode, 0);
KeyEvent up = new KeyEvent(now, now, KeyEvent.ACTION_UP, eventCode, 0);
(IWindowManager.Stub
.asInterface(ServiceManager.getService("window")))
.injectKeyEvent(down, true);
(IWindowManager.Stub
.asInterface(ServiceManager.getService("window")))
.injectKeyEvent(up, true);
} catch (RemoteException e) {
Log.i("Input", "DeadOjbectException");
}
}
private void sendKeyEvent(String event) {
int eventCode = Integer.parseInt(event);
long now = SystemClock.uptimeMillis();
Log.i("SendKeyEvent", event);
try {
KeyEvent down = new KeyEvent(now, now, KeyEvent.ACTION_DOWN, eventCode, 0);
KeyEvent up = new KeyEvent(now, now, KeyEvent.ACTION_UP, eventCode, 0);
(IWindowManager.Stub
.asInterface(ServiceManager.getService("window")))
.injectKeyEvent(down, true);
(IWindowManager.Stub
.asInterface(ServiceManager.getService("window")))
.injectKeyEvent(up, true);
} catch (RemoteException e) {
Log.i("Input", "DeadOjbectException");
}
}
injectKeyEvent是WindowManagerService的public 方法,虽然WindowManagerService被隐藏掉,但是我们可以通过反射来调用injectKeyEvent。
更多精彩
赞助商链接