You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Kaspresso/Kakao/UI Automator从下载文件夹选取文件?

从Android下载文件夹选取文件的实现方案(Kaspresso/Kakao/UI Automator)

一、使用UI Automator实现

UI Automator可以直接操作系统级别的UI组件,适合处理文件选择器这类系统应用:

  • 打开文件选择器后,定位并点击侧边栏/导航栏的「下载」选项(不同设备文本可能为「Download」,需适配)
  • 定位目标文件并完成点击操作

代码示例:

val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())

// 切换到下载文件夹
device.findObject(UiSelector().text("下载")).click()

// 定位并点击目标文件(示例文件名为test.pdf)
val targetFile = device.findObject(UiSelector().text("test.pdf"))
if (targetFile.exists()) {
    targetFile.click()
}

补充:如果文件列表过长,可通过device.swipe()方法滑动查找;也可通过资源ID定位文件名控件,比如UiSelector().resourceId("com.android.documentsui:id/file_name").textContains("test")

二、使用Kaspresso结合Kakao实现

Kaspresso基于Espresso和Kakao封装,可通过屏幕类统一管理元素定位:
首先定义文件选择器的屏幕类:

class FilePickerScreen : Screen<FilePickerScreen>() {
    val downloadTab = KButton { text("下载") }
    val targetFile = KTextView { text("test.pdf") }
}

然后在测试流程中调用:

// 触发文件选择器打开后,执行以下操作
onScreen<FilePickerScreen> {
    downloadTab.click()
    targetFile.click()
}

补充:需确保测试配置允许访问系统组件,比如在测试类添加@SdkSuppress(minSdkVersion = 21)(UI Automator依赖Android 5.0+),同时提前通过adb命令推送测试文件到下载文件夹:adb push local_file.pdf /sdcard/Download/

三、通用注意事项

  • 不同Android版本的文件选择器UI差异较大,需针对目标版本做适配
  • 动态生成的文件名,优先通过文本包含、资源ID等方式定位,避免硬编码完整文件名
  • 测试前需确认下载文件夹权限已授予,避免因权限问题导致元素定位失败

内容的提问来源于stack exchange,提问作者Vladimir Fisher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 20:17:05