Mujiburrohman

ManagePermission

Jul 30th, 2020 (edited)
247
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 2.33 KB | None | 0 0
  1. class ManagePermissions(val context: Context, val list: List<String>, val code:Int) {
  2.  
  3.     // Check permissions at runtime
  4.     fun checkPermissions() {
  5.         if (isPermissionsGranted() != PackageManager.PERMISSION_GRANTED) {
  6.             showAlert()
  7.         } else {
  8.             Toast.makeText(context, "Permissions already granted.", Toast.LENGTH_LONG).show()
  9.         }
  10.     }
  11.  
  12.  
  13.     // Check permissions status
  14.     fun isPermissionsGranted(): Int {
  15.         // PERMISSION_GRANTED : Constant Value: 0
  16.         // PERMISSION_DENIED : Constant Value: -1
  17.         var counter = 0;
  18.         for (permission in list) {
  19.             counter += ContextCompat.checkSelfPermission(context, permission)
  20.         }
  21.         return counter
  22.     }
  23.  
  24.  
  25.     // Find the first denied permission
  26.     fun deniedPermission(): String {
  27.         for (permission in list) {
  28.             if (ContextCompat.checkSelfPermission(context, permission)
  29.                 == PackageManager.PERMISSION_DENIED
  30.             ) return permission
  31.         }
  32.         return ""
  33.     }
  34.  
  35.  
  36.     // Show alert dialog to request permissions
  37.     fun showAlert() {
  38.         val builder = AlertDialog.Builder(context)
  39.         builder.setTitle("Need permission(s)")
  40.         builder.setMessage("Some permissions are required to do the task.")
  41.         builder.setPositiveButton("OK") { _, _ -> requestPermissions() }
  42.         builder.setNeutralButton("Cancel", null)
  43.         val dialog = builder.create()
  44.         dialog.show()
  45.     }
  46.  
  47.  
  48.     // Request the permissions at run time
  49.     fun requestPermissions() {
  50.         val permission = deniedPermission()
  51.         if (ActivityCompat.shouldShowRequestPermissionRationale(context as Activity, permission)) {
  52.             // Show an explanation asynchronously
  53.             Toast.makeText(context, "Should show an explanation.", Toast.LENGTH_LONG).show()
  54.         } else {
  55.             ActivityCompat.requestPermissions(context, list.toTypedArray(), code)
  56.         }
  57.     }
  58.  
  59.  
  60.     // Process permissions result
  61.     fun processPermissionsResult(
  62.         grantResults: IntArray
  63.     ): Boolean {
  64.         var result = 0
  65.         if (grantResults.isNotEmpty()) {
  66.             for (item in grantResults) {
  67.                 result += item
  68.             }
  69.         }
  70.         if (result == PackageManager.PERMISSION_GRANTED) return true
  71.         return false
  72.     }
  73. }
Add Comment
Please, Sign In to add comment