androidandroid-intentandroid-pendingintent

PendingIntent flag changes in Android 14


I want to register PendingIntent for my notifications in app (they are used as widgets with countdown in them or alarm sound on exact time which can be updated or canceled depends on state).

This is code I've used so far:

val alarmPendingIntentFlag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE){
//WHAT TO DO HERE
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S){
  PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
} else { PendingIntent.FLAG_UPDATE_CURRENT }
alarmPendingIntent = PendingIntent.getBroadcast(this, 0,Intent(ALARM_ACTION), alarmPendingIntentFlag)

registerReceiver(alarmReceiver, IntentFilter(ALARM_ACTION))

I had to change it for Android 11+ from

PendingIntent.FLAG_UPDATE_CURRENT to PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT.

Now I have issue again with Android 14.

Targeting U+ (version 34 and above) disallows creating or retrieving a PendingIntent with FLAG_MUTABLE, an implicit Intent within and without FLAG_NO_CREATE and FLAG_ALLOW_UNSAFE_IMPLICIT_INTENT for security reasons. To retrieve an already existing PendingIntent, use FLAG_NO_CREATE, however, to create a new PendingIntent with an implicit Intent use FLAG_IMMUTABLE.

So how can I update this for Android 14 to keep current functionality of updating intent with fresh data when it needs to be updated?

There is PendingIntent.FLAG_ALLOW_UNSAFE_IMPLICIT_INTENT but not sure if this is okay approach.


Solution

  • You don't need to use PendingIntent.FLAG_MUTABLE. You can safely use PendingIntent.FLAG_IMMUTABLE. You don't need to use FLAG_MUTABLE in order to replace the "extras" in a PendingIntent (via PendingIntent.UPDATE_CURRENT).

    FLAG_MUTABLE is only required when the Intent that is wrapped by the PendingIntent that you pass to some other app is allowed to be modified by that app (usually by adding "extras", data, etc.) when the other app actually sends the Intent. See the documentation of PendingIntent.send() and Intent.fillin()