I am continuing with this series of articles with asking for location permissions and getting the actual location from your phone.
The first step for doing this, is to tell the system that you will be requiring location permissions. You do this by adding the following two lines to your manifest file:
You request both permission, just to make sure that you are covered, no matter where you are:
- ACCESS_COARSE_LOCATION – Allows your application to access approximate location derived from network location sources such as cell towers and Wi-Fi.
- ACCESS_FINE_LOCATION – Allows your app to access the precise location.
Your next step is to explicitly ask the user for permission to access the location. For our example I ask for it by pressing a button, but in a real-world application you would ask it when starting up your application/activity.
The requestPermission method will get called when pressing the button to ask for permission. It will first check if the permission is already granted. If it’s not, it requests it, otherwise it does nothing. In the request permission call you can see LOCATION_PERMISSION_CODE. This is just an arbitrary value that you set to indicate to the next method which permission to process.
The next method is onRequestPermissionsResult which automatically gets called after you approve/deny the permission. the requestCode will be set to your LOCATION_PERMISSION_CODE, so that you know which permission you are processing.
After the permissions are in order, it’s time to get the location:
A full implementation can be found here, and the code for the current article in in Activity_2.