How to analyze ANR in sharedPreferences How to analyze ANR in sharedPreferences android android

How to analyze ANR in sharedPreferences


This is due to an existing bug in Android's implementation of SharedPreferences:

https://issuetracker.google.com/issues/117796731

Currently, any use of SharedPreferences.Editor.apply() is like scheduling a time bomb for ANR.


I've figure out what happening.

from three traces, we can see that:
- the shared preferences is blocked by a file sync.
- the fsync is waiting for something(should be disk).
- a thread is doing the disk operation.

After I check the source codes carefully, lots of SP's get/set are used to record states when the app is launched. Mean while, there is a new thread trying to download big data from sever, like .jar or .so .For some old devices, downloading big datas can occur heavy GC and "apache" lib try to log everything by "Wire". So, sometime, it just takes too long and cause the SP time out.

The fix is
- turn off the apache log
- save state in memory and set them together as one object.
- move some background behavior from the initialize part.