Skip to content

Instantly share code, notes, and snippets.

@benjaminRomano
Last active October 24, 2023 00:43
Show Gist options
  • Save benjaminRomano/6b361f4518aa9f8fc9e37cdb7e326d55 to your computer and use it in GitHub Desktop.
Save benjaminRomano/6b361f4518aa9f8fc9e37cdb7e326d55 to your computer and use it in GitHub Desktop.
Permission granter
// Swap out
fun grantAllDangerousPermissions() {
val permissions = mutableListOf(
Manifest.permission.CAMERA,
Manifest.permission.RECORD_AUDIO,
Manifest.permission.GET_ACCOUNTS,
Manifest.permission.READ_CONTACTS,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_BACKGROUND_LOCATION,
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.READ_CALL_LOG,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
).apply {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
add(Manifest.permission.BLUETOOTH_CONNECT)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
add(Manifest.permission.POST_NOTIFICATIONS)
add(Manifest.permission.READ_MEDIA_IMAGES)
add(Manifest.permission.READ_MEDIA_VIDEO)
}
}
grantAllDangerousPermissions(*permissions.toTypedArray())
}
fun grantAllDangerousPermissions(vararg permissions: String) {
repeat(3) {
for (permission in permissions) {
grantPermission(permission)
}
// wait half a second for the result
waitFor(500L)
if (arePermissionsGranted(*permissions)) {
// if permissions granted, return, otherwise let's retry
return
}
}
throw RuntimeException("Failed to grant all required permissions to package [$packageName]")
}
private fun arePermissionsGranted(vararg permissions: String): Boolean {
return try {
val result = uiDevice.executeShellCommand("dumpsys package $packageName")
for (permission in permissions) {
// With the now enforced work accounts, employee devices will have two users
// We naively check for a line stating a given permission is granted.
// However, there may be false positives if the granted permission
// does not correspond to the current user
if (!result.contains("$permission: granted=true") &&
!result.contains("$permission, granted=true")
) {
return false
}
}
true
} catch (e: IOException) {
throw RuntimeException("Failed to check permission to package [$packageName]", e)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment