Ionic – get location permission on android 6

I have a pet project which is building a mobile app using ionic framework. It stopped working on my mobile after upgrading to android 6x. In android 6x, permission was moved from install-time to run-time. This means from now on, users are not granting permissions during installation of apps; rather they’ll be asked to grant permission when they want to use that particular feature in the app. It’s a great idea because if you don’t like to grant one specific permission to an app, you should still be able to use other functionalities.

So, after fixing the issue in my app, I thought it’s worth sharing with others as they may find it useful :). Fixing this issue is pretty simple and straightforward. So, let’s dive in!

Here is how my old codes look like (not exact version though, you got it :p ):

Now we can’t call LocationService.getCoords directly anymore because it’ll fail unless user already granted permission to this app to use location. So let’s ask user to grant permission.

First of all, we need to install a cordova plugin by running the following command in project directory:

cordova plugin add cordova-plugin-android-permissions --save

Then, we gonna write a method, askLocationPermission, for asking permission:

Finally, we can use it just before trying to get coords like:

Notes

  • I read somewhere this (can’t find the link) implementation is backward compatible, which makes sense because in older version of Android you’ll be already granted permission during installation (assuming you’ve mentioned locations permission correctly in your app’s manifest).
  • I’ve used promise in the new method. If you like, you can use callback pattern.
  • For list of available permissions, look at this doc.

ciao!