how to solve `Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent` problem when running android app on android 12 ?
When our app change the target to android sdk 31 or android 12, the app crash and we get this error message:
The key error message is:
2. Reason
Since Android 12 brought important updates to PendingIntents, including the need to explicitly determine if a PendingIntent is mutable, I thought it was worth talking in-depth about what a PendingIntent does, how the system uses it, and why you might need mutable types PendingIntent.
What is pending intent?
Let’s look at the different ways PendingIntents are used in applications, and why we use them.
Basic usage of pending intent:
You can see that we built a standard type of Intent to open our app, and then simply wrapped it with a PendingIntent before adding it to the notification.
In this example, we constructed a PendingIntent that cannot be modified with the FLAG_IMMUTABLE flag because we know exactly what we need to do in the future.
The job is done after calling NotificationManagerCompat.notify(). When the system displays a notification, and the user clicks on the notification, PendingIntent.send() is called on our PendingIntent to start our application.
How to update the immutable pending intent?
You might think that if the application needs to update the PendingIntent, it needs to be a mutable type, but it’s NOT. The PendingIntent created by the application can be updated with the FLAG_UPDATE_CURRENT flag.
3. Solution
So, the final solution is as below:
change from this :
to this:
4. Summary
In this post, I demonstrated how to solve the Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent problem when your android app change target sdk to 31 and above, the key point is adding a PendingIntent.FLAG_IMMUTABLE flag to your PendingIntent. That’s it, thanks for your reading.
Final Words + More Resources
My intention with this article was to help others who might be considering solving such a problem.
So I hope that’s been the case here. If you still have any questions, don’t hesitate to ask me by
email: Email me
Here are also the most important links from this article along with some further resources that will help you in this scope: