Skip to content

Commit

Permalink
Do not write SharedPreferences to disk in the main thread
Browse files Browse the repository at this point in the history
SettingsStore used to call editor.commit() to apply the value of
a setting and write it to disk. That should not be done in the main
thread though as it's a blocking operation. It's better to use
apply() which atomically modifies the SharedPreferences object in
memory and then uses a background thread to write it to disk.

It's safe to replace commit() by apply() as long as the return
value is not used, which is the case.

This fixes reports like:
D  StrictMode policy violation; ~duration=3 ms: android.os.strictmode.DiskWriteViolation
at android.os.StrictMode$AndroidBlockGuardPolicy.onWriteToDisk(StrictMode.java:1615)
at libcore.io.BlockGuardOs.write(BlockGuardOs.java:446)
at libcore.io.ForwardingOs.write(ForwardingOs.java:951)
at libcore.io.IoBridge.write(IoBridge.java:649)
at java.io.FileOutputStream.write(FileOutputStream.java:401)
at com.android.internal.util.FastXmlSerializer.flushBytes(FastXmlSerializer.java:253)
at com.android.internal.util.FastXmlSerializer.flush(FastXmlSerializer.java:274)
at com.android.internal.util.FastXmlSerializer.endDocument(FastXmlSerializer.java:219)
at com.android.internal.util.XmlSerializerWrapper.endDocument(XmlSerializerWrapper.java:68)
at com.android.internal.util.XmlUtils.writeMapXml(XmlUtils.java:408)
at android.app.SharedPreferencesImpl.writeToFile(SharedPreferencesImpl.java:803)
at android.app.SharedPreferencesImpl.access$900(SharedPreferencesImpl.java:59)
at android.app.SharedPreferencesImpl$2.run(SharedPreferencesImpl.java:672)
at android.app.SharedPreferencesImpl.enqueueDiskWrite(SharedPreferencesImpl.java:691)
at android.app.SharedPreferencesImpl.access$100(SharedPreferencesImpl.java:59)
at android.app.SharedPreferencesImpl$EditorImpl.commit(SharedPreferencesImpl.java:604)
at com.igalia.wolvic.browser.SettingsStore.resetCrashRestartCount(SettingsStore.java:766)
at com.igalia.wolvic.VRBrowserActivity.lambda$onCreate$0$com-igalia-wolvic-VRBrowserActivity(VRBrowserActivity.java:296)
at com.igalia.wolvic.VRBrowserActivity$$ExternalSyntheticLambda3.run(D8$$SyntheticClass:0)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:214)
at android.os.Looper.loop(Looper.java:304)
at android.app.ActivityThread.main(ActivityThread.java:7918)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1010)
  • Loading branch information
svillar committed Nov 19, 2024
1 parent daa3e1e commit a086c2a
Showing 1 changed file with 70 additions and 70 deletions.
Loading

0 comments on commit a086c2a

Please sign in to comment.