Skip to content

Instantly share code, notes, and snippets.

@vidyesh95
Created February 9, 2022 17:35
Show Gist options
  • Save vidyesh95/bddbf6480d99a9330c3f59a6ff5a276a to your computer and use it in GitHub Desktop.
Save vidyesh95/bddbf6480d99a9330c3f59a6ff5a276a to your computer and use it in GitHub Desktop.
// Register the permissions callback, which handles the user's response to the system
// permissions dialog. Save the return value, an instance of ActivityResultLauncher.
// You can use either a val, as shown in this snippet, or a lateinit var in your onAttach() or
// onCreate() method.
private val requestPermissionLauncher = registerForActivityResult(
ActivityResultContracts.RequestPermission()
) { isGranted ->
if (isGranted) {
// Permission is granted. Continue the action or workflow in your app.
Log.i("asdf", "Permission granted")
} else {
// Explain to the user that the feature is unavailable because the features requires a
// permission that the user has denied. At the same time, respect the user's decision.
// Don't link to system settings in an effort to convince the user to change their
// decision.
Log.i("asdf", "Permission denied")
}
}
private fun requestCameraPermission() {
when {
ContextCompat.checkSelfPermission(
this,
Manifest.permission.CAMERA
) == PackageManager.PERMISSION_DENIED -> {
// You can use the API that requires the permission.
Log.i("asdf", "Permission previously granted")
}
ActivityCompat.shouldShowRequestPermissionRationale(
this,
Manifest.permission.CAMERA
) -> {
// In an educational UI, explain to the user why your app requires this permission
// for a specific feature to behave as expected. In this UI, include a "cancel" or
// "no thanks" button that allows the user to continue using your app without
// granting the permission.
Log.i("asdf", "Show camera permissions dialog")
}
else -> {
// You can directly ask for the permission.
// The registered ActivityResultCallback gets the result of this request.
requestPermissionLauncher.launch(Manifest.permission.CAMERA)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment