SharedPreferences.apply()和ANR应用程序 [英] SharedPreferences.apply() and ANR application

查看:352
本文介绍了SharedPreferences.apply()和ANR应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾经使用过SharedPreferences.apply()方法.当经常调用此方法时,它将挂起应用程序. Commit()方法非常慢,但是可以正常工作.

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.

在我的示例中,您可以获取ANR.折叠并展开活动!

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;
}
}

折叠并展开活动!

推荐答案

每隔10毫秒,您将无限期地通过apply()调用派生一个后台线程,所有这些线程都会在尝试执行时排队等候/O在相同的数据上.那不会给你好的结果.

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.

除此之外,我将非常小心地以现有方式在线程之间共享Editor实例.

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

这篇关于SharedPreferences.apply()和ANR应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆