Asking for location permission for apps with maps

In Android 6.0 and above, apps now have to get permission from users to access the device’s location data. If you’re targeting API level of 23 or higher, you can use the new permissions model when setting “myLocationEnabled(true)” on your maps model.

I generally like to use fragments when I develop Android apps and most examples online, even the ones on the Google developer website, uses Activity as an example. I will show the code on how to set my location enabled on your GoogleMaps to true inside a fragment. This example is a toy project I’m working on called “Toilet Finder”, which displays a map with the pinned locations of all the public bathrooms in your vicinity. This app will probably be useful when you’re a tourist in a new city and you don’t know where any of the public toilets are.

There are a few important bits in this code.

On the top of the

class, I have the integer constant

I am passing this into the

method in line 61. With this, I have

at the bottom of the class. This override method gets called when the user either accepts or deny the location permission request.

One important point here is that when you can either call requestPermissions or ActivityCompat.requestPermissions(), the latter which you have to pass in your activity to. The former requestPermissions is only usable within a fragment and not anywhere else. If you use the latter, you’ll have to override onRequestPermissionsResult on the activity that is initializing your fragment.

With this, you can have that pretty little location dot on the top-right of your map.