我有使用AlarmManager.setRepeating(..)创建通知的逻辑。我成功创建了一些特殊时间的通知来显示它。在这里,我使用 storeSelectedDays()
将SharedPrefereces值保存为某个ID还有一些BroadcastReceiver在应该显示通知时运行(时机已到)。 在这里,我使用 getStoredSelectedDays()从此ID读取SharedPreferences的值。
public class SelectedDaysManager {
private final static String PREFERENCES_KEYS = "sp_key";
private final static String KEY = "KEY_";
private final SharedPreferences sharedPreferences;
public SelectedDaysManager(Context context) {
sharedPreferences = context.getSharedPreferences(
PREFERENCES_KEYS, Context.MODE_PRIVATE);
}
public List<Integer> getStoredSelectedDays(long id) {
final List<Integer> result = new ArrayList<Integer>();
final Set<String> set = sharedPreferences.getStringSet(KEY + id,
new HashSet<String>());
for (String item : set) {
result.add(Integer.parseInt(item));
}
Log.d("TIME TIME", String.format("Got selected days: KEY = %s,
DAYS = %s", KEY + id, result));
return result;
}
public void storeSelectedDays(long id, List<Integer> selectedDays) {
final Set<String> selectedDaysSet = new HashSet<String>();
for (Integer day : selectedDays) {
selectedDaysSet.add(String.valueOf(day));
}
final SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putStringSet(KEY + id, selectedDaysSet);
editor.commit();
Log.d("TIME TIME", String.format("Saved selected days: KEY = %s,
DAYS = %s", KEY + id, selectedDaysSet));
}
}
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
...
final List<Integer> storedSelectedDays =
App.getInstance().getSelectedDaysManager()
.getStoredSelectedDays(reminderId);
...
}
应用
public class App extends Application {
private static App sInstance = new App();
public static BefitApp getInstance() {
return sInstance;
}
private SelectedDaysManager selectedDaysManager;
@Override
public void onCreate() {
super.onCreate();
sInstance = this;
selectedDaysManager = new SelectedDaysManager(getApplicationContext());
...
}
public SelectedDaysManager getSelectedDaysManager() {
return selectedDaysManager;
}
}
现在,我的问题是:
我保存了2个提醒:
storeSelectedDays(1,/ some int list / [1,2,3]);
storeSelectedDays(2,/ 一些int列表 / [1,2,3]);
在sharedpreferences中的文件看起来像这样:
<?xml version="1.0" encoding="UTF-8" standalone="true"?>
<map>
<set name="KEY_2">
<string>3</string>
<string>2</string>
<string>1</string>
</set>
<set name="KEY_1">
<string>3</string>
<string>2</string>
<string>1</string>
</set>
</map>
但是
当BroadcastReceiver第一次运行时
getStoredSelectedDays(1)返回[1,2,3]
当BroadcastReceiver第二次运行时
getStoredSelectedDays(2)返回[]
所以有些人在第二次运行(id == 2)时设置为空。我做错了什么?
--- --- EDITED
行为:
OMG。这是不可能的