PermissionsKt

Additional

Language
Kotlin
Version
1.0.0 (Mar 5, 2018)
Created
Mar 5, 2018
Updated
Mar 7, 2018
Owner
sembozdemir
Contributor
sembozdemir
1
Activity
Badge
Generate
Download
Source code
APK file

Show card

PermissionsKt

Handle Android Runtime Permissions in Kotlin way

How to add

PermissionsKt is published with JitPack.io. To add this library to your project, add these lines to your build.gradle

repositories {
    maven { url "https://jitpack.io" }
}

dependencies {
    implementation 'com.github.sembozdemir:PermissionsKt:1.0.0'
}

How to use

  • Prepare Manifest

Add the permission to AndroidManifest.xml.

<uses-permission android:name="android.permission.CAMERA"/>

  • Ask for permission

It is so simple. Just ask for permission you want anywhere on your Activity.

askPermissions(Manifest.permission.CAMERA) {
    onGranted {
        showCamera()
    }
}
  • Call delegated function

Call delegated extension function on onRequestPermissionsResult.

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
    handlePermissionsResult(requestCode, permissions, grantResults)
}
  • Other callbacks

You may also listen onDenied, onShowRationale, onNeverAskAgain callbacks if you need. Call request.retry() on action after showing rationale message on onShowRationale.

askPermissions(Manifest.permission.CAMERA) {
    onGranted {
        showCamera()
    }

    onDenied {
        Log.d(TAG, "Camera permission is denied.")
    }

    onShowRationale { request ->
        Snackbar.make(rootView, "You should grant Camera permission", Snackbar.LENGTH_INDEFINITE)
                .setAction("Retry") { request.retry() }
                .show()
    }

    onNeverAskAgain {
        Log.d(TAG, "Never ask again for Camera permission")
    }
}
  • Multiple permissions

You may also ask for multiple permissions at the same time.

askPermissions(Manifest.permission.CALL_PHONE, Manifest.permission.READ_SMS) {
    onGranted {
        makeCall()
        sendSms()
    }

    onDenied { permissions ->
        permissions.forEach {
            when (it) {
                Manifest.permission.CALL_PHONE -> Log.d(TAG, "Call Phone is denied")
                Manifest.permission.READ_SMS -> Log.d(TAG, "Read Sms is denied")
            }
        }
    }

    onShowRationale { request ->
        Snackbar.make(rootView, "You should grant Call Phone and Read Sms permissions, Snackbar.LENGTH_INDEFINITE)
                .setAction("Retry") { request.retry() }
                .show()
    }

    onNeverAskAgain { permissions ->
        permissions.forEach {
            when (it) {
                Manifest.permission.CALL_PHONE -> Log.d(TAG, "Never ask again for Call Phone")
                Manifest.permission.READ_SMS -> Log.d(TAG, "Never ask again for Read Sms")
            }
        }
    }
}

You could view

sample module for more details.