Android 发送按键事件

import android.hardware.input.InputManager;
import android.os.SystemClock;
import android.util.Log;
import android.view.InputDevice;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;

public class InputKey {
    private long mDownTime;
    private int mCode;
    private int mScancode;

    private void sendEvent(int action, long when) {
        final KeyEvent ev = new KeyEvent(mDownTime, when, action, mCode, 0,
                0, KeyCharacterMap.VIRTUAL_KEYBOARD, mScancode, 0
                        | KeyEvent.FLAG_FROM_SYSTEM
                        | KeyEvent.FLAG_VIRTUAL_HARD_KEY,
                InputDevice.SOURCE_KEYBOARD);
        InputManager.getInstance().injectInputEvent(ev,
                InputManager.INJECT_INPUT_EVENT_MODE_ASYNC);
    }
    
    public void inputKeyUpDown(int keyCode) {
        mCode = keyCode;
        mScancode=0;
        mDownTime = SystemClock.uptimeMillis();
        sendEvent(KeyEvent.ACTION_DOWN, mDownTime);
        
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        sendEvent(KeyEvent.ACTION_UP, SystemClock.uptimeMillis());
        
    }


    public void inputKeyUpDown(int keyCode,int scanCode) {
        mCode = keyCode;
        mScancode=scanCode;
        mDownTime = SystemClock.uptimeMillis();
        sendEvent(KeyEvent.ACTION_DOWN, mDownTime);
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        sendEvent(KeyEvent.ACTION_UP, SystemClock.uptimeMillis());
    }
}

推荐阅读更多精彩内容