I am making an alarm app in which the alarm can be set with a toggle button. The code works in ADV
, but if I test it on a real device, the the App closes imediatly after settting the alarm once and then turning it off. Also the alarm does not turn off.
(button press alarmOn -> alarm is on, button press alarmOff-> app closes + alarm is still on)
mStartBtn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
long time;
if (((ToggleButton) view).isChecked()){ //if button is on
Intent intent = new Intent(MainActivity.this, AlarmReceiverActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 2, intent, PendingIntent.FLAG_CANCEL_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, timePicker1.getCurrentHour());
calendar.set(Calendar.MINUTE, timePicker1.getCurrentMinute());
time = (calendar.getTimeInMillis() - (calendar.getTimeInMillis() % 60000));
if (System.currentTimeMillis() > time) {
if (calendar.AM_PM == 0)
time = time + (1000 * 60 * 60 * 12);
else
time = time + (1000 * 60 * 60 * 24);
}
am.set(AlarmManager.RTC_WAKEUP, time, pendingIntent); //sets the alarm
}else{ //if button is off
am.cancel(pendingIntent);
}
}
});
Thank you for helping,
Florian
Your app is basically crashing. Maybe because you are passing null to am.cancel(pendingIntent)
//pendingIntent might be null here.
Try moving PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 2, intent, PendingIntent.FLAG_CANCEL_CURRENT);
outside the if condition. If that is not the case then check AlarmReceiverActivity for crashes.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.