尽管有很多示例表明类似的操作应该有效,但以下代码会失败。
该代码位于与真实项目关联的测试项目中。
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