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.

Leave a Comment