Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grant ACCESS_MOCK_LOCATION permission for testing using adb fails in Marshmallow

Here is the recipe of the problem:

  1. Add mock location permission in debug manifest <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>
  2. Install debug version of application in phone (in Gradle: debug { debuggable true })
  3. Try to give permission with adb: adb shell pm grant com.myapp.name android.permission.ACCESS_MOCK_LOCATION

The outcome of the command is:

Operation not allowed: java.lang.SecurityException: Permission android.permission.ACCESS_MOCK_LOCATION is not a changeable permission type"

If I go to developer options on the phone and set Setting >> Developer Option >> Select Mock location app it works.

I need this for automated tests, so obviously the option of going to the phone settings is not valid because it's reset on every installation of the app, so I need the adb option to work.

like image 961
Sebas LG Avatar asked Feb 07 '23 12:02

Sebas LG


1 Answers

I found the solution inside the Calabash fix for this same problem: https://github.com/calabash/calabash-android/commit/b31be97953325383b9295ff52234a0121cc27e27

adb shell appops set com.myapp.name 58 allow

To do this automatically from gradle you can add the command to the install tasks:

def adb = android.getAdbExe().toString()
tasks.whenTaskAdded { task ->
    if (task.name.startsWith('install')) {
        task.doLast {
            android.applicationVariants.all { variant ->
                "${adb} devices".execute().text.eachLine {
                    if (it.endsWith("device")) {
                        def device = it.split()[0]
                        println "Granting test permissions on device ${device}\n"
                        "${adb} shell appops set ${variant.applicationId} 58 allow".execute()
                    }
                }
            }
        }
    }
}

But you have to explictly call the install task before the connectedTest task, like:

gradlew installMyAppDebug connectedMyAppDebugAndroidTest
like image 70
Sebas LG Avatar answered Feb 13 '23 06:02

Sebas LG