androidannotationscoding-stylelinterror-suppression

Check Android Permissions in a Method


here is my code and it works perfectly fine.

if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
    mMap.setMyLocationEnabled(true);
}

But I don't like such a big code on every check, and want to delegate it to a method in my utility class.

if (Utils.hasMapLocationPermissions(getActivity())) {
    mMap.setMyLocationEnabled(true);
}

But setMyLocationEnabled has annotation @RequiresPermission And thus I can't delegate it to a method, because lint and editor shows it as an error.

Is there some annotation to write on my utility method and suppress lint?

Something like this

@ChecksPermission
public boolean hasMapLocationPermissions(Activity activity) {
  return // my checking logic..
}

Solution

  • You can rename your method such as checkLocationPermission(Activity activity). I´ve discovered that your method's name must start with "check" and end with "Permission" to pass Lint warnings.

    For example:

    public static boolean checkLocationPermission(Context context) {
        return ActivityCompat.checkSelfPermission(context,
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(context,
                Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
    }