Permissions

These code blocks refer to snippets that work on Android permissions.

Sample logic flow for Android location permissions

- Posted in Permissions by

Sample of kotlin code checking if user has already granted permission to access the user's current location data.

// 1️⃣ Check first if users have given permission.

private fun isPermissionGranted() : Boolean {
   return ContextCompat.checkSelfPermission(
        this,
       Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
}

// 2️⃣ If users have given permission, enable the location data layer.
//    If not, prompt user to grant permission. 

private fun enableMyLocation() {
    if (isPermissionGranted()) {
        map.isMyLocationEnabled = true
    }
    else {
        ActivityCompat.requestPermissions(
            this,
            arrayOf<String>(Manifest.permission.ACCESS_FINE_LOCATION),
            REQUEST_LOCATION_PERMISSION
        )
    }
}

// 3️⃣ Callback for the result from requesting permissions.
//    This method is invoked for every call on 
//    requestPermissions(android.app.Activity, String[], int).

override fun onRequestPermissionsResult(
    requestCode: Int,
    permissions: Array<String>,
    grantResults: IntArray) {
    // Check if location permissions are granted  
    // and if so enable the location data layer.
    if (requestCode == REQUEST_LOCATION_PERMISSION) {
        if (grantResults.contains(PackageManager.PERMISSION_GRANTED)) {
            enableMyLocation()
        }
    }
}

  To trigger the check, call the enableMyLocation() function inside the onMapReady block.

Basic permission snippet for Google Maps

- Posted in Permissions by

A simple kotlin snippet to insert if you want to trigger the Android location permission dialog in mobile. The "Toast" part is optional.

        if (ActivityCompat.checkSelfPermission(
            this,
            Manifest.permission.ACCESS_FINE_LOCATION
        ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
            this,
            Manifest.permission.ACCESS_COARSE_LOCATION
        ) != PackageManager.PERMISSION_GRANTED
    ) {


        val text = "No permissions detected!"
        val duration = Toast.LENGTH_SHORT
        val toast = Toast.makeText(applicationContext, text, duration)
        toast.show()


        ActivityCompat.requestPermissions(
            this,
            arrayOf<String>(Manifest.permission.ACCESS_FINE_LOCATION),
            REQUEST_LOCATION_PERMISSION
        )


        return
    }

Remember to place this snippet immediately before the code/feature that requires permissions. For example:

mMap.isMyLocationEnabled = true