4.0之前的模拟按键方法
private void sendKeyEvent(int keyCode) {
int eventCode = keyCode;
long now = SystemClock.uptimeMillis();
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")))
.injectInputEventNoWait(down);
(IWindowManager.Stub
.asInterface(ServiceManager.getService("window")))
.injectInputEventNoWait(up);
} catch (RemoteException e) {
Log.i(TAG, "DeadOjbectException");
}
}
4.0之后的
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();
}
命令行:
input keyevent 66