-
-
Save hichamboushaba/a29b6cbe9fb7cc3e43d2e6160d7b175d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PermissionManager( | |
private val context: Context, | |
private val activityProvider: ActivityProvider | |
) { | |
private val keyIncrement = AtomicInteger(0) | |
fun hasPermission(permission: String): Boolean { | |
return context.checkSelfPermission(permission) == PERMISSION_GRANTED | |
} | |
suspend fun requestPermission(permission: String): PermissionStatus { | |
return requestPermissions(permission)[permission] ?: error("permission result is empty") | |
} | |
suspend fun requestPermissions(vararg permissions: String): Map<String, PermissionStatus> { | |
val currentActivity = activityProvider.currentActivity ?: return permissions.associateWith { | |
PermissionDenied(false) | |
} | |
return suspendCancellableCoroutine { continuation -> | |
val launcher = currentActivity.activityResultRegistry.register( | |
"permission_${keyIncrement.getAndIncrement()}", | |
ActivityResultContracts.RequestMultiplePermissions() | |
) { result -> | |
continuation.resume(permissions.associateWith { | |
if (result[it] == true) { | |
PermissionGranted | |
} else { | |
val shouldShowRationale = | |
currentActivity.shouldShowRequestPermissionRationale(it) | |
PermissionDenied(shouldShowRationale) | |
} | |
}) | |
} | |
launcher.launch(permissions) | |
continuation.invokeOnCancellation { | |
launcher.unregister() | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment