PendingIntent on S+ devices

PendingIntent on S+ devices

One of my Android apps includes a widget that auto-updates both at a fixed interval (AlarmService) and when tapping on the widget. In the past this was accomplished with something like this (C# Xamarin):

PendingIntent pendingIntent = PendingIntent.GetBroadcast(context, 0, intent, 0);

This has worked for years just fine, not realizing that S+ devices (or anything targeting version 31 or above) on Android requires a PendingIntentFlag value in that GetBroadcast call. A brief search returned how “easy” this is, just add in a flag for PendingIntentFlags.UpdateCurrent or PendingIntentFlags.Mutable if you plan on having your intent change itself or accept changes, otherwise use PendingIntentFlags.Immutable. So simple! Uh huh…

Anything besides Immutable throws this error:

Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.'

Right, so my “options” are Immutable only eh? What if instead of relying on an internal Enum I didn’t write we instead grab the expected values for each PendingIntentFlag and force it in? This article explains the expected values for PendingIntentFlags. Changing the above line to this solved the problem (below represents Mutable):

PendingIntent pendingIntent = PendingIntent.GetBroadcast(context, 0, intent, (PendingIntentFlags)33554432);

As always, if you have a better or easier method please share!

Leave a Reply

Your email address will not be published. Required fields are marked *