我有以下PreferenceActivity的Android應用SharedPreferences.Editor時間過長
public class Settings extends PreferenceActivity {
Preference server;
EditTextPreference editServer;
ProgressDialog mDialog;
Handler handler;
Preference bgColor;
EditTextPreference editbgColor;
@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
server = findPreference("webservice");
editServer = (EditTextPreference)server;
bgColor = findPreference("bgColorOption");
editbgColor = (EditTextPreference)bgColor;
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
saveSettings();
}
private void saveSettings() {
SharedPreferences settings = getSharedPreferences("settings", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("Servidor", String.valueOf(editServer.getText().toString()));
editor.putString("bgCor",String.valueOf(editbgColor.getText().toString()));
editor.apply();
}
}
和我的settings.xml文件如下
<?xml version="1.0" encoding="utf-8"?>
<PreferenceCategory android:title="Sistema">
<EditTextPreference
android:dialogMessage="@string/pref_webservice"
android:defaultValue="http://"
android:title="@string/pref_webservice"
android:key="webservice"/>
</PreferenceCategory>
<PreferenceCategory android:title="Aparencia">
<EditTextPreference
android:dialogMessage="@string/BackgroundColorOption"
android:defaultValue="#ffffff"
android:title="@string/BackgroundColorOption"
android:key="bgColorOption" />
</PreferenceCategory>
我的問題是,當我從我的設置活動回去做saveSettings並返回到主要活動,並在我的主要活動onResume函數我應用我的新設置,但他們不立即應用,如果我去設置第二次,然後再回來,然後它。我相信它是因爲我的editor.apply();需要很長時間?任何方式來加快它?
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
SharedPreferences settings = getSharedPreferences("settings", 0);
String server = settings.getString("servidor", "xxx");
String bgColor = settings.getString("bgCor", "#000000");
mDialog.setMessage("A Actualizar...");
thread.setServer(server);
int cor = Color.parseColor(bgColor);
mainLayout.setBackgroundColor(cor);
}
使用'commit()'而不是'apply()' –
考慮將加載/存儲設置移動到異步任務,因爲主線程上的磁盤訪問是反模式。 http://stackoverflow.com/a/4371883/233048 – mach