UiAutomator(2)--UiDevice API

UiAutomator(2)--UiDevice API

一、UiDevice介绍

       1.UiDevice代表设备状态,为单例模式。UiDevice的功能包括:

          (1)获取设备信息:屏幕分辨率,旋转状态,亮灭屏状态等

          (2)操作:案件,坐标操作,滑动,拖拽,灭屏唤醒屏幕,截图等

          (3)监听器功能

       2.UiDevice写法有两种,推荐第一种方式,第二种可能会引起某些问题而导致无法运行:

           (1)UiDevice.getInstance().pressHome();

           (2)getUiDevice().pressHome();


二、API使用

       1. 按键相关的API,常用的按键包括HOME,MENU,BACK,VOLUME_UP,VOLUME_DOWN,RecentApps,POWER等

             (1)pressBack():模拟短按返回back键

             (2)pressEnter():模拟短按回车键

             (3)pressDelete():模拟短按删除delete按键

             (4)pressHome():模拟短按HOME键

             (5)PressMenu():模拟短按menu键

             (6)pressRecentApps():模拟断案最近使用程序

             (7)pressSearch():模拟短按搜索键

             (8)pressKeyCode(int keycode,int metaState):模拟短按键盘代码keycode

                  pressKeyCode(int keyCode):模拟短按键盘代码keycode

                  KEYCODE,键盘映射码,具体见链接:KeyCode

                  KeyEvent,为按键事件,具体见链接:Keyevent

                  metaState为META key的状态。META key是辅助功能键,即ALT、SHIFT、CAPS_LOCK。

                  metaState有四种状态,分别如下:

                  

         2.获取坐标与坐标点击相关API

               (1)click(int x,int y):使用坐标点击屏幕

               (2)getDisplayHeight():返回值为int,获取屏幕高度

               (3)getDisplayWidth():返回值为int,获取屏幕宽度

               (4)getDisplaySizeDp():返回值为Point,获取显示尺寸返回大小(设备独立像素,屏幕旋转返回的显示大小调整)                     DP:设备独立像素,例如,320像素显示到640像素上要拉升一倍

         3.拖拽与滑动相关API

               (1)drag(int startX,int startY,int endX,int endY,int steps):拖动对象从一个坐标拖拽到另一个坐标

               (2)swipe(Point[] segments,int segmentSteps):在点阵列中滑动,5ms一步

               (3)swipe(int startX,int startY,int endX,int endY,int steps):通过坐标滑动屏幕

         4.旋转屏幕API

                (1)setOrinentationLeft():通过禁用传感器,然后模拟设备向左转,并且固定位置

                (2)setOrientationNatural():通过禁用传感器,然后模拟设备转到其自然默认方向,并且固定位置

                (3)setOrienttationRight():通过禁用传感器,然后模拟设备向右转,并且固定位置

                (4)unfreezeRotation():重新启用传感器和允许物理旋转

                (5)isNaturalOrientation():检测设置是否处于默认旋转状态

                (6)getDisplayRotation():返回值为int,返回当前的显示旋转,0度,90度,180度,270度,值分别为:0、1、2、3.

                (7)freezeRotation():禁用传感器和冻结装置物理旋转在其当前旋转状态

         5.灭屏与唤醒屏幕API

                (1)wakeUp():模拟按电源键,如果屏幕是唤醒的没有任何作用

                (2)sleep():模拟按电源键,如果屏幕已经是关闭的则没有任何作用

                (3)isScreenOn():检查屏幕是否亮屏

          6.截图与等待空闲API

                 (1)takeScreenshot(File storePath):把当亲啊窗口截图并将其存储为png默认1.0f的规模(原尺寸)和90%质量,参数为file类的文件路径

                 (2)takeScreenshot(File storePath,float scale,int quality):把当前窗口截图为png格式图片,可以自定义缩放比例与图片质量

                      storePath:存储路径,必须为png格式

                      Scale:缩放比例,1.0为原图

                      Quality:图片压缩质量,范围为0-100

                 (3)waitForIdle(lonog timeout):自定义超时等待当前应用处于空闲状态

                  (4)waitForIdle():等待当前应用处于空闲状态,默认等待10s

                  (5)waitForWindowUpdate(String packageName,long timeout):等待窗口内容更新事件的发生

            7.获取包名&开启通知栏&快速设置&获取布局文件相关API

                  (1)getCurrentPackageName():获取当前界面的包名

                  (2)dumpWindowHierarchy(String fileName):获取当前界面的布局文件,保存在/data/local/tmp/目录下

                  (3)openNotification():打开通知栏

                  (4)openQuickSettings():打开快速设置


三、以自己公司的app为实例

package cn.microinvestment.weitou;

import java.io.File;import java.io.IOException;import android.os.RemoteException;import android.view.KeyEvent;import com.android.uiautomator.core.UiDevice;import com.android.uiautomator.core.UiObject;import com.android.uiautomator.core.UiObjectNotFoundException;import com.android.uiautomator.core.UiSelector;import com.android.uiautomator.testrunner.UiAutomatorTestCase;public class UiDeviceDemo extends UiAutomatorTestCase {    public static void main(String[] args) throws IOException {        Runtime.getRuntime().exec("adb shell am start -n "                + "cn.microinvestment.weitou/cn.microinvestment.weitou.activity.WTLoginControllerActivity");        new UiAutomatorHelper("uiobject", "cn.microinvestment.weitou.UiDeviceDemo", "test", "4");    }    public void test() throws UiObjectNotFoundException, RemoteException{        //登录按enter键(密码用kecode,123456)-获取屏幕高度和宽度-从下往上滑动资讯列表-判断屏幕是否亮,是就灭屏,不是就唤醒        //-截图-获取包名-获取当前界面的布局文件-打开通知栏        UiObject loginbtn=new UiObject(new UiSelector().text("登录"));

       UiObject username=new UiObject(new UiSelector().resourceId("cn.microinvestment.weitou:id/login_phone"));        UiObject password=new UiObject(new UiSelector().resourceId("cn.microinvestment.weitou:id/login_password"));        if(loginbtn.exists()){        loginbtn.clickAndWaitForNewWindow();        //输入登录帐号        username.setText("14900765791");        //点击密码框        password.click();        //用keycode输入123456        UiDevice.getInstance().pressKeyCode(KeyEvent.KEYCODE_1);        UiDevice.getInstance().pressKeyCode(KeyEvent.KEYCODE_2);        UiDevice.getInstance().pressKeyCode(KeyEvent.KEYCODE_3);        UiDevice.getInstance().pressKeyCode(KeyEvent.KEYCODE_4);        UiDevice.getInstance().pressKeyCode(KeyEvent.KEYCODE_5);        UiDevice.getInstance().pressKeyCode(KeyEvent.KEYCODE_6);        UiDevice.getInstance().pressKeyCode(KeyEvent.KEYCODE_ENTER);        UiDevice.getInstance().pressKeyCode(KeyEvent.KEYCODE_ENTER);        UiDevice.getInstance().waitForIdle();        //用keycode按enter键        UiDevice.getInstance().pressKeyCode(KeyEvent.KEYCODE_ENTER);        UiDevice.getInstance().pressKeyCode(KeyEvent.KEYCODE_ENTER);        //默认等待10s        UiDevice.getInstance().waitForIdle();        }        //获取屏幕的宽和高        int x=UiDevice.getInstance().getDisplayWidth();        int y=UiDevice.getInstance().getDisplayHeight();        //从下向上滑动        UiDevice.getInstance().swipe(x/2, y-200, x/2, 200, 100);        UiDevice.getInstance().waitForIdle(20000);        //判断屏幕是否亮        if(!UiDevice.getInstance().isScreenOn()){            UiDevice.getInstance().wakeUp();        }        UiDevice.getInstance().waitForIdle(5000);        //截图        UiDevice.getInstance().takeScreenshot(new File("/sdcard/test.png"));        //获取当前的包名        System.out.println(UiDevice.getInstance().getCurrentPackageName());        //获取当前的布局        UiDevice.getInstance().dumpWindowHierarchy("1.xml");        //打开通知栏        UiDevice.getInstance().openNotification();    }}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个简单的使用`UiAutomator2`框架编写的测试用例示例: ```java import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.uiautomator.By; import androidx.test.uiautomator.UiDevice; import androidx.test.uiautomator.Until; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(AndroidJUnit4.class) public class MyUiAutomatorTest { private UiDevice mDevice; @Before public void setUp() throws Exception { // 获取UiDevice实例 mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()); // 按Home键回到主屏幕 mDevice.pressHome(); // 等待Launcher界面出现 mDevice.wait(Until.hasObject(By.pkg(getLauncherPackageName()).depth(0)), 5000); } @Test public void testOpenSettings() throws Exception { // 打开应用列表 mDevice.pressRecentApps(); // 等待应用列表出现 mDevice.wait(Until.hasObject(By.res("com.android.systemui:id/recents_view")), 5000); // 找到设置应用并点击 mDevice.findObject(By.text("设置")).click(); // 等待设置应用打开 mDevice.wait(Until.hasObject(By.pkg("com.android.settings").depth(0)), 5000); // 验证是否成功打开了设置应用 assertEqual("com.android.settings", mDevice.getCurrentPackageName()); } private String getLauncherPackageName() throws Exception { // 获取默认的Launcher应用包名 final Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); PackageManager pm = InstrumentationRegistry.getContext().getPackageManager(); ResolveInfo resolveInfo = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY); return resolveInfo.activityInfo.packageName; } } ``` 这个测试用例会执行以下操作: 1. 回到主屏幕 2. 打开应用列表 3. 打开“设置”应用 4. 验证是否成功打开了“设置”应用 您可以根据自己的需求编写更复杂的测试用例,例如在应用程序中执行用户操作、验证应用程序的UI元素等。需要注意的是,`UiAutomator2`框架只能在Android 4.3或更高版本上运行。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值