我一直在处理这个问题一整天。问题是,当我尝试在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;
}
}
}
我不知道如何解决这个问题。
如果有任何帮助或建议,我将不胜感激。
答案 0 :(得分:1)
Android管理滑动对象的方式并不是那么清楚。 当您尝试拖动某些内容时,Android会生成一张跟随您的手指的图片,并为您提供拖动的概念。 问题是产生该效果的系统组件不是来自您的应用程序,而是来自另一个应用程序,因此Android认为在拖动过程中您正在触摸另一个应用程序&#34;。 不小心碰到系统键盘时会出现同样的问题。
解决方案是使用系统证书对apk进行签名,并在清单上添加INJECT_EVENTS权限。