Android Studio | java + uiautomator实现自动化截图并保存

1、配好环境(网上很多不细讲)

①app下的build.gradle

dependencies {

    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    implementation files('libs\\uiautomator.jar')
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    androidTestImplementation 'com.android.support.test.uiautomator:uiautomator-v18:2.1.2'
}

②jar包
在这里插入图片描述

2、在这个文件夹下新建一个类:

在这里插入图片描述

3、编辑这个类

package com.example.uiautomatortestapp;

import android.app.Instrumentation;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObjectNotFoundException;
import android.util.Log;

import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;

import org.junit.Test;
import org.junit.runner.RunWith;

import java.io.File;

@RunWith(AndroidJUnit4.class)
public class TestClass {

    private static Instrumentation mInstrumentation;
    public static UiDevice mUidevices;
    public static String TAG = "BaseTest";

    public static void setup() {
        //一些初始化
        Log.e(TAG, "测试前");
        mInstrumentation = InstrumentationRegistry.getInstrumentation();
        mUidevices = UiDevice.getInstance(mInstrumentation);
        try {
            mUidevices.wakeUp();
        } catch (Exception e) {
        }
    }

    public static void sleep(long time) {
        try {
            Thread.sleep(time);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test000() throws UiObjectNotFoundException {
        setup();
        //路径:“/data/data/你的包名/随便一个名字.png”
        mUidevices.getInstance().takeScreenshot(new File("/data/data/com.example.uiautomatortestapp/test1.png"));
        sleep(500);

    }
}

4、运行入口调整

①方法一
在这里插入图片描述
②方法二
在这里插入图片描述

5、查看结果

在这里插入图片描述

6、备注

我运行的环境是设备,不是AVD哦
截图成果应该是运行TestClass时设备上实时显示的界面哦

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值