Delete Delete Permission

I use android studio and compileSdkVersion is 23 in that I use below code

if(locationManager != null){ locationManager.removeUpdates(GPSListener.this); } 

to stop the gps update, where the GPS receiver is the class that implements the LocationListener.

but in the removeUpdates line I get below the lint warning

A call requires permission, which can be rejected by the user: the code must explicitly check whether the permission is available (with checkPermission ) or handle the potential SecurityException

I do not understand what the problem is in the above code. Any additional permissions needed to be added to the manifest file ?.

Sincerely.

+8
android android location
source share
4 answers

Starting with SDK 23, you need / need to check the resolution before you look at the API functions. Here is an example of how to do this:

 if (locationManager != null) { if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { locationManager.removeUpdates(GPSListener.this); } } 

There is checkSelfPermission() , which should check if "you" (this application) have the correct permissions. There is also checkPermission() , which should check if the other process has the correct permissions.

Notes

  • next to doing this runtime check, you still need to require the appropriate permissions in AndroidManifest.
  • if your targetSdk is <23, you should use ContextCompat.checkSelfPermission() instead (thanks JerryBrady)
+26
source share

I was unable to use checkSelfPermission() because my minimum API is 14 and 23. Knowing this, you can also try before catch a SecurityException .

Example:

 try { locationManager.removeUpdates(GPSListener.this); } catch (SecurityException e) { Log.e("PERMISSION_EXCEPTION","PERMISSION_NOT_GRANTED"); } 
+14
source share

To add to Jerry Brady's comment regarding ContextCompat, this will be the full code for <23:

  if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) 
+5
source share

Here is my solution!

  if (Build.VERSION.SDK_INT >= 23) { if (checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { lm.removeUpdates(this); } } else { lm.removeUpdates(this); } 
-one
source share

All Articles