How can I send key events in android?

天大地大妈咪最大 提交于 2019-11-28 06:38:17
Roman Trokhymets
BaseInputConnection  mInputConnection = new BaseInputConnection(targetView, true);
mInputConnection.sendKeyEvent(new KeyEvent(...));

you can try this

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

of course, you can choose command input text ... for input a text.

None of these are valid. To go to Home screen from use below code.

Intent home = new Intent(Intent.ACTION_MAIN);
home.addCategory(Intent.CATEGORY_HOME);
//home.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(home);

If you are not calling from activity/fragment you may have to uncomment the flag part. For going back below code works on some devices.

dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));

Let me know if this helps!

Lotfi

Here are some precision to Roman answer

BaseInputConnection  mInputConnection = new BaseInputConnection( findViewById(R.id.main_content), true);
KeyEvent kd = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MENU);
KeyEvent ku = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MENU);
mInputConnection.sendKeyEvent(kd);
mInputConnection.sendKeyEvent(ku);

There is also InputConnection's sendKeyEvent function. InputConnection is only API Level 3.

Reviving old thread - You can perform Home and Back with the relatively new Accessibility API - Check out "performGlobalAction" here: http://developer.android.com/reference/android/accessibilityservice/AccessibilityService.html

(Specifically with the GLOBAL_ACTION_HOME and GLOBAL_ACTION_BACK actions)

Of course you will need appropriate permissions for an Accessibility Service, but this does not require root

You can try this.

long now = SystemClock.uptimeMillis();
BaseInputConnection mInputConnection = new BaseInputConnection(findViewById(R.id.MainActivity), true);
KeyEvent down = new KeyEvent(now, now, KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_HOME, 0);
mInputConnection.sendKeyEvent(down);

This code can work for me.

Note : Please remember to replace the "R.id.MainActivity" to your Activity name.

It works for me:

public static void simulateKey(final int KeyCode) {

    new Thread() {
        @Override
        public void run() {
            try {
                Instrumentation inst = new Instrumentation();
                inst.sendKeyDownUpSync(KeyCode);
            } catch (Exception e) {
                Log.e("Exception when sendKeyDownUpSync", e.toString());
            }
        }

    }.start();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!