How can I send key events in android?

2019-01-17 09:18发布

I am macking a custom navigation bar to Android 4.0.3.r1 and want to send key events like "Home" and "Back". My application is not a system therefore:

IWindowManager mWindowManager = IWindowManager.Stub.asInterface(
                ServiceManager.getService(Context.WINDOW_SERVICE));
mWindowManager.injectKeyEvent( ev, false );

It doesn't work, because I can not get android.permission.INJECT_EVENTS from not system application. How can I do this?

8条回答
孤傲高冷的网名
2楼-- · 2019-01-17 09:20
BaseInputConnection  mInputConnection = new BaseInputConnection(targetView, true);
mInputConnection.sendKeyEvent(new KeyEvent(...));
查看更多
等我变得足够好
3楼-- · 2019-01-17 09:22

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

查看更多
smile是对你的礼貌
4楼-- · 2019-01-17 09:22

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);
查看更多
Viruses.
5楼-- · 2019-01-17 09:26

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

查看更多
混吃等死
6楼-- · 2019-01-17 09:28

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();
}
查看更多
一纸荒年 Trace。
7楼-- · 2019-01-17 09:38

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.

查看更多
登录 后发表回答