android – 如何在向ActivityInstrumentationTestCase2测试发送触摸时修复INJECT_EVENT权限异常

虽然有很多例子表明这样的东西应该起作用,但是下面的代码失败了.

此代码存在于与实际项目关联的测试项目中.

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);
    }

}

这引发了一个
    java.lang.SecurityException:注入另一个应用程序需要INJECT_EVENTS权限
在i.sendPointerSync()调用上.
我也尝试过view.onTouchEvent(event)和view.dispatchTouchEvent(event)但没有成功.

我唯一能想到的是,如果这个例子在正在测试的项目中有效.这看起来很糟糕,因为建议将测试分离到不同的项目,并能够从构建服务器运行它们,例如:

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

最佳答案 这可能意味着您的主项目,测试项目或模拟器版本不同步.

点赞