尽管有很多例子表明这样的事情应该可以工作,但下面的代码失败了。此代码位于与实际项目关联的测试项目中。
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: Injecting to another application requires INJECT_EVENTS 对 i.sendPointerSync() 调用的权限。我也试过 view.onTouchEvent(event) 和 view.dispatchTouchEvent(event) 没有成功。
我唯一能想到的是,如果这个工作的例子在被测试的项目中生活。这似乎很糟糕,因为建议是将测试分开到不同的项目,并能够从构建服务器运行它们,例如:
adb -e shell am instrument -w com.mypackage.activities.test/android.test.InstrumentationTestRunner