How to specify mutable pending intent in Android 12?

Viewed 693

I am aware there's tons of similar questions, but I cannot find anything that answers this one particular one.

I am trying to update my app to use a mutable PendingIntent. I know that for Android 12+, I can do

PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, updateIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE);

However, my app has a minSdk of 24 and PendingIntent.FLAG_MUTABLE was added in sdk 31. When I try this

PendingIntent pendingIntent = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
   pendingIntent = PendingIntent.getBroadcast(context, 0, updateIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE);
} else {
   pendingIntent = PendingIntent.getBroadcast(context, 0, updateIntent, PendingIntent.FLAG_UPDATE_CURRENT);
}

I get a warning in the else block in Android Studio for "Missing Pending Intent Mutability Flag". Is this an Android Studio bug? Or do I need to do something else to handle mutable pending intents?

1 Answers

You don't need the if block. You can just use:

PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
                updateIntent, PendingIntent.FLAG_UPDATE_CURRENT |
                              PendingIntent.FLAG_MUTABLE);

even though the constant PendingIntent.FLAG_MUTABLE was introduced in API 31, this code will work on older versions of Android as this flag will just be ignored by versions of Android older than API 31.

Related