---
# System prepended metadata

title: 2020-04-20 | Kotlin | Permissions
tags: [android, kotlin, gobelins]

---

# 2020-04-20 | Kotlin | Permissions

###### tags: `kotlin` `android` `gobelins`

## Variables
```
val requestCodePermission = 0
```

## onCreateView
```kotlin
if(ContextCompat.checkSelfPermission(
        context,
        android.Manifest.permission.ACCESS_FINE_LOCATION
    ) != PackageManager.PERMISSION_GRANTED
) {
    // Verifier si l'utilisateur a déjà refusé la permission
    if(ActivityCompat.shouldShowRequestPermissionRationale(
            activity as Activity,
            android.Manifest.permission.ACCESS_FINE_LOCATION
        )
    ) {
        // utilisateur a deja refusé la permission, popup d'explication
    } else {
        // Demander la permission
        ActivityCompat.requestPermissions(
            activity as Activity,
            arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),
            requestCodePermission
        )
    }
} else {
    // Continuer car la permission est accordée
}
```

## Dans la classe
```kotlin
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        when(requestCode) {
            requestCodePermission -> {
                if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED))  {
                    // Permission accordée

                } else {
                    // Permission refusée
                    // Désactiver certaines fonctionalités
                    // Afficher un message d'erreur
                }
            }
            else -> {
                // le code ne concerne pas la permission, on ignore
            }
        }
    }
```