1. 程式人生 > >Android模擬傳送按鍵功能的兩種方法

Android模擬傳送按鍵功能的兩種方法


第一種adb命令傳送,缺點:傳送鍵值響應慢。

    private void sendVirtualKey(int keycode){
        try
        {
            String keyCommand = "input keyevent " + KeyEvent.KEYCODE_VOLUME_UP;
            Runtime runtime = Runtime.getRuntime();
            Process proc = runtime.exec(keyCommand);
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

第二種是虛擬鍵盤傳送方式:

    private void keyRemappingSendFakeKeyEvent(int action, int keyCode) {
        long eventTime = SystemClock.uptimeMillis();
        if (action == KeyEvent.ACTION_DOWN) {
            mKeyRemappingSendFakeKeyDownTime = eventTime;
        }

        KeyEvent keyEvent = new KeyEvent(mKeyRemappingSendFakeKeyDownTime, eventTime, action, keyCode, 0);
        InputManager inputManager = (InputManager) mContext.getSystemService(Context.INPUT_SERVICE);
        inputManager.injectInputEvent(keyEvent, InputManager.INJECT_INPUT_EVENT_MODE_ASYNC);
    }