简体   繁体   English

如何请求 Android Marshmallow 的权限以进行 JUnit 测试

[英]How to request permissions on Android Marshmallow for JUnit tests

I want to execute JUnit tests against my lib and want to ask user to grant all required permissions before the test starts (because I need to read some files from device storage during the automated tests for example).我想对我的库执行 JUnit 测试,并希望在测试开始之前要求用户授予所有必需的权限(因为我需要在自动测试期间从设备存储中读取一些文件)。

I know how to make it by adding a task to gradle and run it from cmd, it is working well.我知道如何通过向 gradle 添加任务并从 cmd 运行它来实现它,它运行良好。 But I need to ask user (or do it automatically) when I ran my tests using IDE .但是当我使用 IDE运行测试时,我需要询问用户(或自动执行)。

I've tried to add permission request to MainActivity.onCreate() of test app but no luck because MainActivity starts not for all tests.我尝试向测试应用程序的 MainActivity.onCreate() 添加权限请求,但没有成功,因为 MainActivity 并非针对所有测试启动。

Do anyone have any ideas?有人有什么想法吗?

Also, please do not talk about adding gradle grant task to execution configuration.另外,请不要谈论将 gradle 授权任务添加到执行配置中。 it is working but unusable, needs something more unified.它正在工作但无法使用,需要更统一的东西。

I found a solution to my problem. 我找到了解决问题的方法。 It was easy: 很容易:

needs to create a new task in app-level build.gradle file like this: 需要在应用程序级别的build.gradle文件中创建一个新任务,如下所示:

android.applicationVariants.all { variant ->
    def applicationId = variant.applicationId
    def adb = android.getAdbExe().toString()
    def variantName = variant.name.capitalize()
    def grantPermissionTask = tasks.create("create${variantName}Permissions") << {
        println "Granting permissions"
        "${adb} shell pm grant ${applicationId} android.permission.ACCESS_FINE_LOCATION".execute()
        "${adb} shell pm grant ${applicationId} android.permission.WRITE_EXTERNAL_STORAGE".execute()
        "${adb} shell pm grant ${applicationId} android.permission.READ_EXTERNAL_STORAGE".execute()
    }
}

then add the following dependency: 然后添加以下依赖项:

preBuild.dependsOn "createDebugPermissions"

after that, all required permissions will be granted when you run any test 之后,当您运行任何测试时,将授予所有必需的权限

A better way, since API version 23 (Android M): 从API版本23(Android M)开始,一种更好的方法:

@Rule
public GrantPermissionRule mRuntimePermissionRule = GrantPermissionRule.grant(Manifest.permission.ACCESS_FINE_LOCATION);
...

Logcat warning seems to be recommending uiAutomation.grantRuntimePermission instead of pm grant. Logcat 警告似乎推荐 uiAutomation.grantRuntimePermission 而不是 pm grant。

Instead of adb shell command, we can use (without deprecated methods) in kotlin..代替 adb shell 命令,我们可以在 kotlin..

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
getInstrumentation().uiAutomation.grantRuntimePermission(ApplicationProvider.getApplicationContext<Context>().packageName, "android.permission.BLUETOOTH")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM