How can I send key events in android?
Asked Answered
S

9

13

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?

Sack answered 23/10, 2012 at 8:39 Comment(0)
F
7
BaseInputConnection  mInputConnection = new BaseInputConnection(targetView, true);
mInputConnection.sendKeyEvent(new KeyEvent(...));
Fulgurating answered 13/8, 2013 at 6:41 Comment(1)
Hey what the targetView in this case will be and how to extract it if the user is on homescreen. ThanksDownbeat
L
7

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);
Listless answered 13/1, 2017 at 15:58 Comment(1)
Is it possible to send any kind of key ? All unicode characters?Atthia
A
4

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();
}
Aristotelianism answered 26/8, 2013 at 17:15 Comment(1)
Wnen I use these methods it gives me error about INJECT_EVENTS permission. So I follow this post: #5383901. When I include the permission android.permission.INJECT_EVENTS in manifest file, then it throws an error that permission is granted to system apps. How can I include this permission ? ThanksDownbeat
C
4

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.

Carmina answered 14/11, 2013 at 2:13 Comment(3)
Hi, I tried using this to implement my back button but it didn't work. I'm building for Android 4.4.3. I have searched a lot for a week but no success so far. ThanksDownbeat
if you use this method, you need get root previlegeCarmina
This require issue with root as Runtime.getRuntime().exec(new String[] { "su", "-c","input keyevent "+KeyEvent.KEYCODE });Sporangium
V
2

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!

Vegetal answered 26/9, 2016 at 15:29 Comment(1)
KEYCODE_BACK is for simulating back button action and to generate click event requires both ACTION_DOWN and then ACTION_UP.Vegetal
P
2

I'm also having this same problem before, In below way I solve theKEY_INJECT_EVENT_PERMISSION issue.

Step 1: You need to get the Signature (for me the file name is signapk) of your Device ROM.

Step 2: Then you need to get the platform.pk8 and platform.x509.pem files.

Step 3: Generate the the debug apk of your application.

Step 4: Place all the above files in a single folder.

Step 5: Once you get all the above files run the command mentioned in below.

java -jar signapk.jar platform.x509.pem platform.pk8 your_debug_app.apk customname.apk

Step 6: After this you can get a signed apk (customname.apk) in the same folder.Once you get that run the below command.

adb install -r app-release-signed.apk

Step 7: Now the Inject_Event_Permisson will be enabled.

Polo answered 11/9, 2019 at 12:23 Comment(0)
S
0

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

Saturated answered 14/5, 2013 at 16:5 Comment(0)
T
0

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

Typhoon answered 26/11, 2015 at 22:9 Comment(1)
I don't wanna listen to events, I wanna send event (back key), how to make that in code using AccessibilityService?Allocution
S
0

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.

Stockish answered 18/8, 2016 at 11:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.