Last active
January 23, 2021 16:57
-
-
Save afreakyelf/91a9d5e854a26bea287c0f7233086929 to your computer and use it in GitHub Desktop.
Ask for Runtime Permissions in Android
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
private val requiredPermissionList = arrayOf( | |
//list of permissions | |
Manifest.permission.WRITE_EXTERNAL_STORAGE, | |
Manifest.permission.READ_EXTERNAL_STORAGE | |
) | |
private fun checkAndRequestPermission(): Boolean { | |
val permissionsNeeded = ArrayList<String>() | |
for (permission in requiredPermissionList) { | |
if (ContextCompat.checkSelfPermission(this, permission) != | |
PackageManager.PERMISSION_GRANTED | |
) { | |
permissionsNeeded.add(permission) | |
} | |
} | |
if (permissionsNeeded.isNotEmpty()) { | |
ActivityCompat.requestPermissions( | |
this, | |
permissionsNeeded.toTypedArray(), | |
PERMISSION_CODE | |
) | |
return false | |
} | |
return true | |
} | |
override fun onRequestPermissionsResult( | |
requestCode: Int, | |
permissions: Array<out String>, | |
grantResults: IntArray | |
) { | |
when (requestCode) { | |
PERMISSION_CODE -> if (grantResults.isNotEmpty()) { | |
val readPermission = grantResults[0] == PackageManager.PERMISSION_GRANTED | |
val writePermission = grantResults[1] == PackageManager.PERMISSION_GRANTED | |
if (readPermission && writePermission) | |
launchPdf() | |
else { | |
Toast.makeText(this, " Permission Denied", Toast.LENGTH_SHORT).show() | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment