Android模拟用户点击的实现方法

时间:2021-05-20

前言

Android模拟用户点击。在自动化测试中可使用的工具。

可以利用adb命令,也可以使用Android SDK中的monkeyrunner工具。

  • win7-64
  • gitbash

使用adb命令

主要使用input命令

usage: input ... input text <string> input keyevent <key code number or name> input tap <x> <y> input swipe <x1> <y1> <x2> <y2>

keyevent指的是android对应的keycode,比如home键的keycode=3,back键的keycode=4

tap是touch屏幕的事件,只需给出x、y坐标即可

swipe模拟滑动的事件,给出起点和终点的坐标即可

编写一个bat脚本,模拟用户滑动

@echo offecho --------- Mock start ----------:tag_startecho running...adb shell input swipe 650 250 200 666@ping 127.0.0.1 -n 8 >nulgoto tag_startecho --------- Mock finish ---------pause

死循环发送滑动命令,延时语句@ping 127.0.0.1 -n 8 >nul

monkeyrunner

环境配置,配置好Java与Android SDK的环境变量。手机连接到电脑。
系统变量中加入ANDROID_SWT,此例中路径为G:\SDK\tools\lib\x86_64

修改后的脚本rustmonkeyrunner.bat,Windows环境下需要在gitbash或CMD里运行

来自unable-to-access-jarfile-framework-monkeyrunner-25-3-2-jar

@echo offrem Copyright (C) 2010 The Android Open Source Projectremrem Licensed under the Apache License, Version 2.0 (the "License");rem you may not use this file except in compliance with the License.rem You may obtain a copy of the License atremrem http://.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImageprint("waiting for connection...")device = MonkeyRunner.waitForConnection()print("device found!")s_wid = int(device.getProperty("display.width")) # 获取屏幕宽度像素s_height = int(device.getProperty("display.height")) # 获取屏幕高度像素print("build.version.sdk " + str(device.getProperty("build.version.sdk")))print("display.width " + str(s_wid))print("display.height " + str(s_height))drag_point_left_x = 20drag_point_right_x = s_wid - 20drag_point_y = s_height / 2for i in range(0, 10): print("current loop is " + str(i)) device.drag((drag_point_right_x, drag_point_y), (drag_point_left_x, drag_point_y), 1.0, 50) print("waiting...") MonkeyRunner.sleep(1) print("continue") device.drag((drag_point_left_x, drag_point_y), (drag_point_right_x, drag_point_y), 0.5, 3) MonkeyRunner.sleep(3)print("-------- finish --------")

命令行直接执行,可以看到执行结果和相应的报错信息

C:\Users\Administrator>G:\SDK\tools\bin\rustmonkeyrunner.bat H:\fisher_p\py_ws\an_test2.pyimporting module...waiting for connection...device found!build.version.sdk 23display.width 1440display.height 2560current loop is 0waiting...continuecurrent loop is 1# .....-------- finish --------

测试中发现,脚本可以运行在系统app。若当前打开的是第三方app,会直接报错,获取不到相应信息

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章