How to fix INJECT_EVENT permission exception when sending touches to an ActivityInstrumentationTestCase2 test

时光总嘲笑我的痴心妄想 提交于 2019-12-12 09:43:21

问题


Although there are many examples showing that something like this should work, the following code fails. This code lives in a test project that is associated with the real project.

public class MyTest extends ActivityInstrumentationTestCase2<MyActivity> {

    public MyTest(String name)
    {
        super("com.mypackage.activities", MyActivity.class);
        setName(name);
    }

    public void testTap() throws Throwable
    {
        //Required by MotionEvent.obtain according to JavaDocs
        long downTime = SystemClock.uptimeMillis();
        long eventTime = SystemClock.uptimeMillis();

        Instrumentation i = getInstrumentation();

        //Setup the info needed for our down and up events to create a tap
        MotionEvent downEvent = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_DOWN, 300, 20, 0);
        MotionEvent upEvent = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_UP, 300, 20, 0);

        //Send the down/up tap event
        i.sendPointerSync(downEvent);
        i.sendPointerSync(upEvent);

        //Delay to see the results
        Thread.currentThread().sleep(3000);
    }

}

This throws a java.lang.SecurityException: Injecting to another application requires INJECT_EVENTS permission on the i.sendPointerSync() calls. I have also tried view.onTouchEvent(event) and view.dispatchTouchEvent(event) without success.

The only thing I can think of is if the examples where this is working live in the project being tested. This seems bad because the recommendation is to separate tests to a different project and be able to run them from a build server with something like:

adb -e shell am instrument -w com.mypackage.activities.test/android.test.InstrumentationTestRunner

回答1:


This probably means that your main project, your test project or your emulator versions are out of sync.




回答2:


It might help others.

Problem we got is

Failed to perform gesture. java.lang.SecurityException: Injecting to another application requires INJECT_EVENTS permission (RuntimeError")

In my case, the problem was with the

Network not connected

. Once fixed the network connection issue, tests are started running.



来源:https://stackoverflow.com/questions/10423240/how-to-fix-inject-event-permission-exception-when-sending-touches-to-an-activity

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