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

查看:23
本文介绍了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() 调用分叉一个后台线程,所有这些都将排队当他们试图对相同的数据进行 I/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天全站免登陆