Should accessing SharedPreferences be done off the UI Thread?

前端 未结 6 1045
执笔经年
执笔经年 2020-11-29 15:41

With the release of Gingerbread, I have been experimenting with some of the new API\'s, one of them being StrictMode.

I noticed that one of the warnings is for

6条回答
  •  余生分开走
    2020-11-29 16:27

    One subtlety about Brad's answer: even if you load the SharedPreferences in onCreate(), you should probably still read values on the background thread because getString() etc. block until reading the shared file preference in finishes (on a background thread):

    public String getString(String key, String defValue) {
        synchronized (this) {
            awaitLoadedLocked();
            String v = (String)mMap.get(key);
            return v != null ? v : defValue;
        }
    }
    

    edit() also blocks in the same way, although apply() appears to be safe on the foreground thread.

    (BTW sorry to put this down here. I would have put this as a comment to Brad's answer, but I just joined and don't have enough reputation to do so.)

提交回复
热议问题