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