Skip to content

Instantly share code, notes, and snippets.

@johnny3young
Created January 2, 2020 18:52
Show Gist options
  • Save johnny3young/9ad68c478a80aeb5b95a00578d94755d to your computer and use it in GitHub Desktop.
Save johnny3young/9ad68c478a80aeb5b95a00578d94755d to your computer and use it in GitHub Desktop.
// List with required permissions
private val REQUIRED_SDK_PERMISSIONS = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)
private fun checkPermissions() {
val missingPermissions = ArrayList<String>()
// check all required dynamic permissions
for (permission in REQUIRED_SDK_PERMISSIONS) {
val result = ContextCompat.checkSelfPermission(this, permission)
if (result != PackageManager.PERMISSION_GRANTED) {
missingPermissions.add(permission)
}
}
if (!missingPermissions.isEmpty()) {
// request all missing permissions
val permissions = missingPermissions.toTypedArray()
ActivityCompat.requestPermissions(this, permissions, REQUEST_CODE_ASK_PERMISSIONS)
} else {
val grantResults = IntArray(REQUIRED_SDK_PERMISSIONS.size)
Arrays.fill(grantResults, PackageManager.PERMISSION_GRANTED)
onRequestPermissionsResult(
REQUEST_CODE_ASK_PERMISSIONS, REQUIRED_SDK_PERMISSIONS,
grantResults
)
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
when (requestCode) {
REQUEST_CODE_ASK_PERMISSIONS -> {
for (index in permissions.indices) {
when (grantResults[index]) {
PackageManager.PERMISSION_GRANTED -> {
LoginActivity.start(this as Context)
finish()
}
PackageManager.PERMISSION_DENIED -> {
val showRationale =
ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[index])
if (showRationale) {
val builder = AlertDialog.Builder(this)
builder.setMessage(getString(R.string.rationale_permission_message))
.setTitle("Permission required")
builder.setPositiveButton(
"OK"
) { dialog, id ->
checkPermissions()
}
val dialog = builder.create()
dialog.show()
} else {
val builder = AlertDialog.Builder(this)
builder.setMessage(getString(R.string.mandatory_permission_message))
.setTitle("Permission required")
builder.setPositiveButton(
"OK"
) { dialog, id ->
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
val uri = Uri.parse("package:" + applicationContext.packageName)
intent.data = uri
startActivity(intent)
}
val dialog = builder.create()
dialog.show()
}
}
}
}
}
else -> {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment