如何在GMD Android测试设备(ATD)上授予运行时及特殊权限
解决ATD/GMD设备上特殊权限授予问题
针对ATD(Android测试设备)上无法通过常规方法授予特殊权限(如WRITE_SETTINGS)的问题,可通过以下两种有效方案解决:
方案一:CI/CD预执行ADB命令
在测试启动前,直接通过ADB命令修改系统权限状态,跳过设置应用的交互流程:
# 授予WRITE_SETTINGS权限 adb shell appops set com.your.app.package WRITE_SETTINGS allow # 若需其他特殊权限,例如SYSTEM_ALERT_WINDOW adb shell appops set com.your.app.package SYSTEM_ALERT_WINDOW allow
这种方式适合在CI/CD流水线中集成,提前完成权限配置,避免测试过程中出现崩溃。
方案二:测试代码中动态处理
在测试类的初始化阶段,判断当前设备是否为ATD,然后通过UiAutomation执行shell命令授予权限:
import android.app.UiAutomation; import android.os.ParcelFileDescriptor; import androidx.test.platform.app.InstrumentationRegistry; import org.junit.Before; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; public class YourTestClass { @Before public void setupPermissions() { if (isATDDevice()) { String targetPackage = InstrumentationRegistry.getInstrumentation().getTargetContext().getPackageName(); // 授予WRITE_SETTINGS权限 executeShellCommand("appops set " + targetPackage + " WRITE_SETTINGS allow"); // 按需添加其他特殊权限 executeShellCommand("appops set " + targetPackage + " SYSTEM_ALERT_WINDOW allow"); } } private boolean isATDDevice() { // 通过设备属性判断是否为ATD设备 String productModel = executeShellCommand("getprop ro.product.model"); String productName = executeShellCommand("getprop ro.product.name"); return productModel.contains("ATD") || productName.contains("atd"); } private String executeShellCommand(String command) { StringBuilder result = new StringBuilder(); try { UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation(); ParcelFileDescriptor pfd = uiAutomation.executeShellCommand(command); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(pfd.getFileDescriptor()))); String line; while ((line = reader.readLine()) != null) { result.append(line); } reader.close(); pfd.close(); } catch (IOException e) { e.printStackTrace(); } return result.toString().trim(); } }
原理说明
- ATD是专为自动化测试优化的设备,允许直接通过
appops命令修改权限状态,无需依赖设置应用 appops命令直接操作系统权限管理模块,绕过了常规的Intent请求流程,彻底避免ActivityNotFoundException- 测试代码中通过
UiAutomation执行shell命令,无需额外权限配置(插桩测试默认拥有INJECT_EVENTS权限)
注意事项
- 不同特殊权限对应不同的
appops操作符,可通过adb shell appops list命令查看完整权限列表 - 该方案同时适用于GMD(Gradle托管设备),因为GMD本质基于ATD镜像构建
- 确保测试的Instrumentation配置中已启用
android:targetPackage和必要的测试权限
内容的提问来源于stack exchange,提问作者Elec0
相关产品推荐
相关产品推荐

