0

我有一个应用程序,当应用程序第一次运行时,我设置了大约 200 个共享首选项。我最初是通过从我的 onCreate 方法调用它来加载所有首选项

SharedPreferences pref = getSharedPreferences(CALC_PREFS, MODE_PRIVATE);
settingsEditor = prefs.edit();
settingsEditor.putString("Something", "");
....
settingsEditor.commit();

它会运行得很好而且相当快。然后我重新设计了我的应用程序,使其具有一个抽象活动类来处理所有使用共享首选项的工作,因为我有 4 个不同的活动访问这些首选项。

public abstract class AnActivity extends Activity{

// Shared Preference string
private static final String CALC_PREFS = "CalculatorPrefs";
// Editor to customize preferences
private Editor settingsEditor;
// Shared preference
private SharedPreferences prefs;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    prefs = getSharedPreferences(CALC_PREFS, MODE_PRIVATE);
    settingsEditor = prefs.edit();
}

protected void addPref(String key, String value){
    settingsEditor.putString(key, value).commit();
}

protected void addPref(String key, int value){
    settingsEditor.putInt(key, value).commit();
}
//other methods were not posted    
}

我的主要活动没有扩展“AnActivity”类。但是,当我在全新安装上运行我的应用程序或尝试访问任何共享首选项时,实例化所有内容需要 10 秒以上的时间。

How can I set the default values in a clean and efficient manner? Does creating an Abstract class to handle the preferences create more overhead than just calling getSharedPreferences manually?

4

1 回答 1

1

Are you commiting each time you add a preference? This is probably your issue, commiting for each entry could be quite expensive, batch together your put's and commit once.

If you don't need to specify the default value, you could always use clear() instead

http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#clear%28%29

于 2012-09-28T15:51:00.563 回答