我目前将我的服务的最后更新时间存储在首选项中:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM HH:mm:ss");
String now = sdf.format(new Date());
Editor edit = PreferenceManager
.getDefaultSharedPreferences(this).edit();
edit.putString("lastUpdate", now);
edit.commit();
Log.i(this.getClass().toString(),"***** SERVICE: "+now+" *****");
// Done with our work... stop the service!
AlarmService_Service.this.stopSelf();
这工作得很好,但是当我想在我的 PrefenceActivity 中显示它时问题就来了。
事实上,似乎我必须强制停止应用程序以使 PreferenceActivity 显示最新值。
这是一个例子:
应用程序于 20:50 开始
服务于20:50开始
=> PrefenceActivity 显示 20h50...听起来不错
服务于 21:00 开始
=> PrefenceActivity 仍然显示 20h50!!!
服务于21:10开始
=> PrefenceActivity 仍然显示 20h50!!!
然后在 21:12,=> PrefenceActivity 仍然显示 20h50!!!
21:12 我强制关闭应用程序并再次打开它:
=> PrefenceActivity 最终显示最新值 (21:10)
真不明白是怎么回事,好像是Service期间Prefence没有更新!!!
public class PreferenceActivity extends SherlockPreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
setSummaryAll(this.getPreferenceScreen());
}
private void setSummaryAll(PreferenceScreen pScreen) {
for (int i = 0; i < pScreen.getPreferenceCount(); i++) {
Preference pref = pScreen.getPreference(i);
updatePref(pref);
}
}
public void updatePref(Preference pref) {
if (pref instanceof ListPreference) {
final ListPreference listPref = (ListPreference) pref;
listPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
listPref.setSummary(listPref.getEntries()[listPref
.findIndexOfValue(newValue.toString())]);
return true;
}
});
pref.setSummary(listPref.getEntry());
} else if (pref instanceof EditTextPreference) {
Log.i("***", "EditTextPreference " + pref.getKey());
final EditTextPreference etPref = (EditTextPreference) pref;
etPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
etPref.setSummary(newValue.toString());
return true;
}
});
pref.setSummary(etPref.getText());
}
}
}