Application.Quit() closes application before SharedPreferences in-memory changes are committed to disk. #27585
Labels
area-essentials
Essentials: Device, Display, Connectivity, Secure Storage, Sensors, App Info
platform/android 🤖
s/triaged
Issue has been reviewed
s/verified
Verified / Reproducible Issue ready for Engineering Triage
t/bug
Something isn't working
Milestone
Description
Calling
Application.Quit()
immediately after using thePreferences
API toSet()
changes will cause the changes to be lost. This is because thePreferences
API on Android uses theSharedPreferences.Editor.apply()
method, which writes changes to memory and begins asynchronously writing the changes to disk.According to the Android documentation on the
SharedPreferences.Editor.apply()
method:This seems to suggests that even if the app is closed, any changes applied using an
ISharedPreferencesEditor
should be allowed to finish writing to disk before the app is closed. This seems to work with the standard app lifecycle (i.e. being dismissed or closed by the user), but not after callingApplication.Quit()
.It's also worth noting that calling
Application.Quit()
doesn't cause theOnDestroy()
delegate to be invoked either. Using something likePlatform.CurrentActivity.FinishAffinity()
does cause theOnDestroy()
delegate to be invoked, but it still won't ensure thatSharedPreferences
edits are committed to disk before the app closes.Steps to Reproduce
Debug
for me, since it is time-sensitive you may need to build using theRelease
configuration depending on your hardware.Application.Quit()
.ISharedPreferencesEditor.Commit()
until the changes are written to disk before callingApplication.Quit()
.Link to public reproduction project repository
https://github.com/NathanielJS1541/MauiApplicationQuitBug
Version with bug
8.0.100 SR10
Is this a regression from previous behavior?
No, this is something new
Last version that worked well
Unknown/Other
Affected platforms
Android
Affected platform versions
Presumably all Android versions. Tested on Android 8.1, Android 12, and Android 14.
Did you find any workaround?
Before calling
Application.Quit()
, you can use the following code to block until the asynchronous disk writes are finished:Note
Although
PreferenceManager.GetDefaultSharedPreferences()
is marked as deprecated, it is still in use in Precerences.Android.cs in the MAUI source.This workaround assumes you are using the default
SharedPreferences
file. If not, use the following:This works because, according to the Android documentation on
ISharedPreferencesEditor.Apply()
:Therefore, as long as you call
Commit()
on aSharedPreferences
editor for the same file you applied changes to, it will block until all asynchronous disk writes are completed, regardless of whether you made any new changes or not.Relevant log output
The text was updated successfully, but these errors were encountered: