07月08, 2015

几种模拟按键的方法

模拟按下物理按键的方法:

1.

Runtime runtime=Runtime.getRuntime();

 try {
  runtime.exec("input keyevent " + KeyEvent.KEYCODE_BACK);

} catch (IOException e) {
 e.printStackTrace();
 }

2.


new Thread(new Runnable() {
@Override
public void run() {


Instrumentation inst = new Instrumentation();
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
}
}).start();

3.


Thread sendKey = new Thread(){
            public void run() {
                try {                    
                    long now = SystemClock.uptimeMillis();
                    KeyEvent keyDown = new KeyEvent(now, now, KeyEvent.ACTION_DOWN,
                            keyCode, 0);
                    IWindowManager wm = IWindowManager.Stub.asInterface(
                            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();
                }
            }
        };
        sendKey.start();

本文链接:http://www.siki.space/post/somg_way_to_simulate_key_press.html

-- EOF --

Comments