Location Manager remove updates permission

£可爱£侵袭症+ 提交于 2019-12-03 13:12:29

Since SDK 23, you should/need to check the permission before you call Location API functionality. Here is an example of how to do it:

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 is to check if 'you' (this app) has the correct permissions. There is also checkPermission(), which is to check if another process has the correct permissions.

Notes

  • next to doing this runtime check, it is still also necessary to require the relevant permissions in the AndroidManifest.
  • if your targetSdk is < 23, you should use ContextCompat.checkSelfPermission() instead (thanks to JerryBrady)
Rodrigo Borba

I wasn't able to use checkSelfPermission(), because my min API is 14 and 23 is required. Knowing that, you can also try to catch a SecurityException.

Example:

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

To add to Jerry Brady's comment regarding ContextCompat, this is 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)

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);

            }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!