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);
    }





你可能感兴趣的:(代码记忆,原创,控件)