Simulate a key press on Android

Method 1:

import android.app.Instrumentation;

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



Method 2:

import android.view.inputmethod.BaseInputConnection;
import android.view.KeyEvent;

BaseInputConnection inputConnection = new BaseInputConnection(edittext1, true);
inputConnection.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_1));


你可能感兴趣的:(Android)