我有一种方法可以设置我想要触发警报的时间。在这种方法中,我还有一个取消警报的停止按钮
if(alarmManager != null){
alarmManager.cancel(pi);
}
我的问题是,当我设置警报时,退出应用程序并再次取消警报,我得到一个 nullPointer。我猜这是因为当我离开应用程序时 PendingIntent 也会关闭(设置为 null)。
我怎样才能防止这种情况发生,以便我可以取消警报?
这是整个方法:
@SuppressWarnings("deprecation")
public void setTime(){
Calendar mcurrentTime = Calendar.getInstance();
int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
int minute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener()
{
int callCount = 0; //To track number of calls to onTimeSet()
@Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute)
{
if(callCount == 1) // On second call
{
String timeString = "";
timeString = selectedHour + ":" + selectedMinute + ":00";
Log.d("TEST", "Chosen time : "+ timeString);
setAlarm(timePicker, selectedHour, selectedMinute);
}
callCount++; // Incrementing call count.
}
}, hour, minute, true);
mTimePicker.setButton(DialogInterface.BUTTON_POSITIVE, "Set", mTimePicker);
mTimePicker.setButton(DialogInterface.BUTTON_NEGATIVE, "Stop", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(alarmManager != null){
alarmManager.cancel(pi);
}
}
});
mTimePicker.setTitle(R.string.time);
mTimePicker.show();
}