androidandroid-intentflagslinter

AGP 8 linter asks to add flag to pendingIndent that does not exist in API yet


Recently I updated my Android app:

Before that my linter was working fine and didn't show any issues with the code. However after upgrade it started showing me error:

<Path to file>:<line> Error: Missing PendingIntent mutability flag [UnspecifiedImmutableFlag]
              pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

I know that from API 31 it is required to provide mutability flag for all pending intents, so that's why it is considered as error, but this line comes from fragment:

if(Build.VERSION.SDK_INT >= VERSION_CODES.M){
    pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_IMMUTABLE);
} else {
    pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
}

If I am correct, FLAG_IMMUTABLE was introduced in API 23, so if I want to support also API 21 and 22 I need to have that "if statement". And if it was introduced in API 23, why linter requires from me to put that flag in code for older APIs?

Am I missing something or is it obvious false positive?

For now I suppressed this error with annotations, but I feel like it is not the right way.


Solution

  • I looked into source code of unit tests for that rule in AGP linter. They are testing it in various ways but they do not test it with code like mine. So based on Android Code Search I was able to fix my problem with code like:

    PendingIntent pendingIntent = null;
    int pendingIntentFlags;
    if(Build.VERSION.SDK_INT >= VERSION_CODES.M){
        pendingIntentFlags = PendingIntent.FLAG_IMMUTABLE;
    } else {
        pendingIntentFlags = 0;
    }
    pendingIntent = PendingIntent.getBroadcast(context, 0, intent, pendingIntentFlags);
    

    Now linter has no problems with that code.

    I still do not know why my previous code was failing on linter, so if anyone have any idea, please share your thoughts in comments because I would like to know.