在使用uiautomator自動化測試框架過程當中,基於對控件實現長按,發現uiautomator自帶的方法longClick()不少時候不能實現對控件的長按,所以須要重寫該方法。node
主要代碼以下:android
public static boolean longClickWithTime(UiObject obj, long time) throws Exception { Class<?> InteractionControllerClass = null; Method findAccessibilityNodeInfoMethod = null; Method getInteractionControllerMethod = null; Method touchDownMethod = null; Method touchUpMethod = null; Field WAIT_FOR_SELECTOR_TIMEOUT = null; findAccessibilityNodeInfoMethod = UiObject.class.getDeclaredMethod("findAccessibilityNodeInfo",long.class); findAccessibilityNodeInfoMethod.setAccessible(true); WAIT_FOR_SELECTOR_TIMEOUT = UiObject.class.getDeclaredField("WAIT_FOR_SELECTOR_TIMEOUT"); WAIT_FOR_SELECTOR_TIMEOUT.setAccessible(true); AccessibilityNodeInfo node = (AccessibilityNodeInfo) findAccessibilityNodeInfoMethod.invoke(obj, WAIT_FOR_SELECTOR_TIMEOUT.getLong(obj)); if(node == null) { throw new UiObjectNotFoundException(obj.getSelector().toString()); } Rect rect = obj.getVisibleBounds(); getInteractionControllerMethod = UiObject.class.getDeclaredMethod("getInteractionController"); getInteractionControllerMethod.setAccessible(true); Object interactionController = getInteractionControllerMethod.invoke(obj); InteractionControllerClass = Class.forName("com.android.uiautomator.core.InteractionController"); touchDownMethod = InteractionControllerClass.getDeclaredMethod("touchDown", int.class, int.class); touchDownMethod.setAccessible(true); touchUpMethod = InteractionControllerClass.getDeclaredMethod("touchUp", int.class, int.class); touchUpMethod.setAccessible(true); if(Boolean.parseBoolean(touchDownMethod.invoke(interactionController, rect.centerX(), rect.centerY()).toString())) { SystemClock.sleep(time); if(Boolean.parseBoolean(touchUpMethod.invoke(interactionController, rect.centerX(), rect.centerY()).toString())) { return true; } } return false; }
調用方式:
在使用uiautomator自動化框架時,調用longClickWithTime(Object, time)方法來實現對UiObject控件長按效果。其中Object參數:uiautomator UiObject控件對象,time:表示長按時間,單位爲毫秒。
例如:對手機主頁時鐘按鈕進行長按5s操做,
longClickWithTime(new UiCollection(new UiObject(new UiSelector().text("Clock")), 5000);框架