【发布时间】:2017-04-06 20:34:11
【问题描述】:
我一整天都在处理这个问题。问题是当我尝试在 Instrumental Espresso 测试中拖动某些东西时出现以下错误。
Caused by: android.support.test.espresso.InjectEventSecurityException: java.lang.SecurityException: Injecting to another application requires INJECT_EVENTS permission
当我调用这个方法时会发生这种情况
onView(withId(R.id.any_id)).perform(CustomViewActions.touchAndDrag(200, 200));
自定义方法
public static ViewAction touchAndDrag(final float x, final float y, final long delay) {
return new ViewAction() {
@Override
public void perform(UiController uiController, final View view) {
// Get view absolute position
sendLinearSwipe(uiController,coordinatesClickOn,coordinatesMoveTo,precision,2000);
};
}
而swipeLinaer 取自 Espresso 的来源
private static Swiper.Status sendLinearSwipe(UiController uiController, float[] startCoordinates,
float[] endCoordinates, float[] precision, int duration) {
checkNotNull(uiController);
checkNotNull(startCoordinates);
checkNotNull(endCoordinates);
checkNotNull(precision);
float[][] steps = interpolate(startCoordinates, endCoordinates, SWIPE_EVENT_COUNT);
final int delayBetweenMovements = duration / steps.length;
MotionEvent downEvent = MotionEvents.sendDown(uiController, startCoordinates, precision).down;
try {
for (int i = 0; i < steps.length; i++) {
if (!MotionEvents.sendMovement(uiController, downEvent, steps[i])) {
Log.e(TAG, "Injection of move event as part of the swipe failed. Sending cancel event.");
MotionEvents.sendCancel(uiController, downEvent);
return Swiper.Status.FAILURE;
}
long desiredTime = downEvent.getDownTime() + delayBetweenMovements * i;
long timeUntilDesired = desiredTime - SystemClock.uptimeMillis();
if (timeUntilDesired > 10) {
uiController.loopMainThreadForAtLeast(timeUntilDesired);
}
}
if (!MotionEvents.sendUp(uiController, downEvent, endCoordinates)) {
Log.e(TAG, "Injection of up event as part of the swipe failed. Sending cancel event.");
MotionEvents.sendCancel(uiController, downEvent);
return Swiper.Status.FAILURE;
}
} finally {
downEvent.recycle();
}
return Swiper.Status.SUCCESS;
}
问题是这不起作用只有在触摸时设置了监听器
这样
anyView.setOnTouchListener(new MyTouchListener());
所以设置什么样的监听器真的无关紧要,但设置的事实会导致错误。
private final class MyTouchListener implements View.OnTouchListener {
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
ClipData data = ClipData.newPlainText("", "");
View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(
view);
view.startDrag(data, shadowBuilder, view, 0);
view.setVisibility(View.INVISIBLE);
return true;
} else {
return false;
}
}
}
我不知道如何解决这个问题。
如果有任何帮助或建议,我将不胜感激。
【问题讨论】:
标签: java android android-espresso android-testing