Skip to content

Instantly share code, notes, and snippets.

@dp-singh
Created March 8, 2021 07:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dp-singh/f1ada523bb17daacc53492b9d01f0719 to your computer and use it in GitHub Desktop.
Save dp-singh/f1ada523bb17daacc53492b9d01f0719 to your computer and use it in GitHub Desktop.
Auto Grant Requested Permissions to Self if Device Admin is enabled. MDM
private fun Activity.autoGrantRequestedPermissionsToSelf(componentName: ComponentName) {
val permissions: List<String> = retrievePermissions(this)
val mDevicePolicyManager = this.getSystemService(AppCompatActivity.DEVICE_POLICY_SERVICE) as DevicePolicyManager
if (mDevicePolicyManager.isAdminActive(componentName)) {
Log.d("PERMISSION", "Device Admin enabled")
} else {
Log.d("PERMISSION", "Device Admin Disabled")
}
for (permission in permissions) {
val result = mDevicePolicyManager.getPermissionGrantState(componentName, packageName, permission)
Log.e(permission, result.toString())
val success: Boolean = mDevicePolicyManager.setPermissionGrantState(componentName, packageName, permission, DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED)
Log.d("PERMISSION", "Auto-granting $permission, success: $success")
if (!success) {
Log.e("PERMISSION", "Failed to auto grant permission to self: $permission")
}
}
}
private fun retrievePermissions(context: Context): List<String> {
return try {
context.packageManager
.getPackageInfo(context.packageName, PackageManager.GET_PERMISSIONS)
.requestedPermissions.toList()
} catch (e: PackageManager.NameNotFoundException) {
throw RuntimeException("This should have never happened.", e)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment