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
This probably means that your main project, your test project or your emulator versions are out of sync.
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