I'm trying to get the GPS coordinates to display when I click a button in my activity layout. The following is the method that gets called when I click the button:
public void getLocation(View view) {
TextView tv = (TextView) findViewById(R.id.gps_coord_view);
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
tv.setText("Latitude: " + loc.getLatitude() + "\nLongitude: " + loc.getLongitude());
}
I'm getting an error that says
Call requires permission which may be rejected by user. Code should explicitly check to see if permission is available.
I have already granted these permissions in my AndroidManifest
. The error is taken care of and the app compiles when I add the following before calling lm.getLastKnownLocation
:
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
However, the app crashes when I press the button that calls getLocation when it's clicked. What is going on? Is there better/simpler way to grab the GPS coordinates of the device?
With Android API level (23), we are required to check for permissions. https://developer.android.com/training/permissions/requesting.html
I had your same problem, but the following worked for me and I am able to retrieve Location data successfully:
(1) Ensure you have your permissions listed in the Manifest:
(2) Ensure you request permissions from the user:
(3) Ensure you use ContextCompat as this has compatibility with older API levels.
(4) In your location service, or class that initializes your LocationManager and gets the last known location, we need to check the permissions:
(5) This approach only worked for me after I included @TargetApi(23) at the top of my initLocationService method.
(6) I also added this to my gradle build:
Here is my LocationService for reference:
I tested with an Android Lollipop device so far only. Hope this works for you.
SIMPLE SOLUTION
I wanted to support apps pre api 23 and instead of using
checkSelfPermission
I used a try / catchThe last part of the error message you quoted states:
...with ("checkPermission") or explicitly handle a potential "SecurityException"
A much quicker/simpler way of checking if you have permissions is to surround your code with
try { ... } catch (SecurityException e) { [insert error handling code here] }
. If you have permissions, the 'try' part will execute, if you don't, the 'catch' part will.if you are working on dynamic permissions and any permission like ACCESS_FINE_LOCATION,ACCESS_COARSE_LOCATION giving error "cannot resolve method PERMISSION_NAME" in this case write you code with permission name and then rebuild your project this will regenerate the manifest(Manifest.permission) file.
Use my custome class to check or request permisson