开发android小闹钟的程序时,在添加闹钟时闹钟列表中总是出现两个相同的闹钟。
btnAddAlarm.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) {
if(tpd == null){
addAlarm();
} tpd.show();
}
});
private void addAlarm() { TimePickerDialog.OnTimeSetListener otsl = new OnTimeSetListener() { @Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar setTime = Calendar.getInstance();
setTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
setTime.set(Calendar.MINUTE, minute);
setTime.set(Calendar.SECOND,0);
setTime.set(Calendar.MILLISECOND, 0); Calendar currentTime = Calendar.getInstance(); if (setTime.getTimeInMillis() <= currentTime.getTimeInMillis()) {
setTime.setTimeInMillis(setTime.getTimeInMillis()+ 24 * 60 * 60 * 1000);
} adapter.add(new AlarmData(setTime.getTimeInMillis())); alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
setTime.getTimeInMillis(), 5 * 60 * 1000,
PendingIntent.getBroadcast(getContext(),
new AlarmData(setTime.getTimeInMillis()).getId(),
new Intent(getContext(),
AlarmReceiver.class), 0)); saveAlarmList(); }
}; Calendar c = Calendar.getInstance();
int hourOfDay = c.get(Calendar.HOUR_OF_DAY);
int min = c.get(Calendar.MINUTE);
tpd = new TimePickerDialog(getContext(), otsl, hourOfDay, min, true);
}
刚开始以为是adapter的问题,于是在初始化函数中加了添加闹钟的代码,结果只有一个闹钟。最后确定是TimePickerDialog的问题,上网查找才知道这是android4.1和4.2的bug,需要重写TimePickerDialog中的onStop方法,把onStop()中super.onStop()注释掉就行了
tpd = new TimePickerDialog(getContext(), otsl, hourOfDay, min, true){
@Override
protected void onStop() {
//super.onStop();
}
};