uiautomator自动化框架实现对控件的长按功能

本文介绍了一种在UIAutomator框架中对控件实现长按效果的方法。通过重写longClick()方法,利用反射机制实现了更精确的长按操作。文中详细展示了核心代码及调用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在使用uiautomator自动化测试框架过程中,基于对控件实现长按,发现uiautomator自带的方法longClick()很多时候不能实现对控件的长按,因此需要重写该方法。

主要代码如下:

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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值