SharedPreferences.apply() and ANR application

落花浮王杯 提交于 2019-12-12 04:54:52

问题


I used to SharedPreferences.apply() method. When this method is called very often, then it hangs the application. Commit() method is very slow, but is working properly.

You can get the ANR in my example. Fold and unfold the activity!

public class Main extends Activity {

@Override
public void onCreate(Bundle b) {
    super.onCreate(b);
    setContentView(R.layout.main);

    new Thread(new Runnable() {
        @Override
        public void run() {

            while(true) {
                SharedPreferences.Editor ed = getEditor();
                ed.putString(getUUID(), getUUID());
                ed.apply();


                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }).start();
}



public static String getUUID() {
    return UUID.randomUUID().toString();
}


final private String BASE = "BASE";
private SharedPreferences shadPrefBase = null;
SharedPreferences getSharedPreferences() {
    if(shadPrefBase == null) {
        shadPrefBase = getSharedPreferences(BASE, Context.MODE_MULTI_PROCESS);
    }
    return shadPrefBase;
}


private SharedPreferences.Editor editorShared = null;
private SharedPreferences.Editor getEditor() {
    if(editorShared == null) {
        editorShared = getSharedPreferences().edit();
    }
    return editorShared;
}
}

Fold and unfold the activity!


回答1:


Every 10 milliseconds, indefinitely, you are forking a background thread via the apply() call, all of which are going to queue up as they attempt to do I/O on the same data. That is not going to give you good results.

Beyond that, I would be very careful about sharing Editor instances across threads the way you are.



来源:https://stackoverflow.com/questions/29166812/sharedpreferences-apply-and-anr-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!