Android :java.lang.SecurityException: Injecting to another application requires INJECT_EVENTS permission

I had the same problem, and my code was something like this (for a normal login activity):

    onView(withId(R.id.username))
            .perform(new TypeTextAction("test_user"));
    onView(withId(R.id.password))
            .perform(new TypeTextAction("test123"));
    onView(withId(R.id.login)).perform(click());

The last line was crashing with SecurityException. Turned out after the last text typing, the keyboard was left open, hence the next click was considered on a different application.

To fix this, I simply had to close the keyboard after typing. I also had to add some sleep to make sure the keyboard is closed, otherwise the test would break every now and then. So the final code looked like this:

    onView(withId(R.id.username))
            .perform(new TypeTextAction("test_user"));
    onView(withId(R.id.password))
            .perform(new TypeTextAction("test123")).perform(closeSoftKeyboard());
    Thread.sleep(250);
    onView(withId(R.id.login)).perform(click());

This worked just fine.


I had the same issue and adding the closeSoftKeyboard() method resolved it for me.

onView(withId(R.id.view)).perform(typeText(text_to_be_typed), closeSoftKeyboard());

I solved using replaceText instead of TypeText action, my code:

onView(withId(R.id.username_edit_text)).perform(ViewActions.replaceText("user123"))

onView(withId(R.id.password_edit_text)).perform(ViewActions.replaceText("pass123"), closeSoftKeyboard())

It's because your device is locked/any other open dialog box is open /anything preventing the test's ability to click on the button. Eg. if the phone is locked-when the test tries to click on the button it can't because the device is locked.

I was having troubles on the emulator because it always displayed "launcher has crashed". So whenever it tried to click the button, it couldn't because the alert dialog box was open.

In short, make sure your screen is unlocked and no message boxes are interfering with the test and it's ability to click on a button.