Warning to check permission still shown if checkSelfPermission() extracted to a method

Viewed 509

I get why Android Studio shows the MissingPermission warning.

Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with checkPermission) or explicitly handle a potential SecurityException less... (⌘F1)

If there is an @RequiresPermission annotated method, the permission needs to be checked. So to prevent the warning, I need to do:

if (ActivityCompat.checkSelfPermission(this,
        Manifest.permission.PERMISSION) == PackageManager.PERMISSION_GRANTED) {
    methodThatNeedsAPermission();
}

Now, this is quite a long code to have in a condition check. Moreover, I want my code to be clean, I want to extract the check to keep business logic and UI / Context-related Android code separated, so I'd like to have:

public void startDoingSomething() {
    if (hasPermission()) {
        methodThatNeedsAPermission();
    }
}

...

public boolean hasPermission() {
    return ActivityCompat.checkSelfPermission(this,
        Manifest.permission.PERMISSION) == PackageManager.PERMISSION_GRANTED;
}

But with this, Android Studio still shows the warning.

Of course, I could suppress the warning with @SuppressLint("MissingPermission") but why should I? I am checking for the permission.

Is there a clean way to get around this? Some kind of annotation I'd add to hasPermission() method so that Android Studio knows that I am checking for the permission?

1 Answers

I had a situation like this and the solution was to follow this path

File > Settings > Editor > inspections > Android click down pointer
Lint click down pointer > Correctness click down pointer
then under Messages scroll down to Missing Permissions un-check the box
Click Apply and OK

Lint is great but not always correct

Related