Android simulate key press

前端 未结 2 526
小鲜肉
小鲜肉 2020-11-28 13:27

How can I programmatically simulate a key press on a Droid? I would like to mimic a manual key press (appearing on the droid that someone is pressing a key but it is being

相关标签:
2条回答
  • 2020-11-28 13:59

    You can use instrumentation, ie following code called from onCreate of your activity will cause menu to be opened and closed multiple times:

        new Thread(new Runnable() {         
            @Override
            public void run() {
                try {
                Instrumentation inst = new Instrumentation();
                for ( int i = 0; i < 10; ++i ) {
                    inst.sendKeyDownUpSync(KeyEvent.KEYCODE_MENU);
                    Thread.sleep(2000);
                    inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
                    Thread.sleep(2000);
                }
                }
                catch(InterruptedException e){
                }
            }   
        }).start();
    

    ...but I am not sure if this is what you are after

    0 讨论(0)
  • 2020-11-28 14:03

    If you have a view that want to consume the event you can use BaseInputConnection class and its sendKeyEvent method.

    To use it you will need to specify a target view (e.g an EditText) that will receive the KeyEvent. For example:

    EditText editText;
    BaseInputConnection inputConnection = new BaseInputConnection(editText, true);
    inputConnection.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_POUND));
    

    The result of this is like user would actually pressed # key (while having the edit text focused).

    0 讨论(0)
提交回复
热议问题