Several things are wrong here:
1 Don't use Intent.FILL_IN_DATA
in the call to PendingIntent.getBroadcast()
. This is an Intent
flag and not a PendingIntent
flag. It doesn't belong here.
2 When you use the PendingIntent.FLAG_NO_CREATE
this will return null
if the PendingIntent
doesn't already exist. In your code to set alarmUp
you've got the comparison against null
backwards. NOTE: See my comments at the end of this answer about the fact that the documentation for this is wrong
3 In your onCreate()
you are doing this:
PendingIntent sender1 = PendingIntent.getBroadcast(getApplicationContext(), 2,
alarmintent, PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA);
This line will create the PendingIntent
even if you don't set an alarm with it. Later, when you check if the PendingIntent
exists with this code:
boolean alarmUp = (PendingIntent.getBroadcast(AlarmActivity.this, 2,
alarmintent, PendingIntent.FLAG_NO_CREATE) == null);
alarmUp
will always be false
, because you have already created the PendingIntent
in onCreate()
.
NOTE: The PendingIntent
is created when you call PendingIntent.getBroadcast()
, not when you set the alarm.
EDIT: Add more code examples
As I said earlier, you can't create the PendingIntent
if you want to use it to determine whether the alarm is set or not. You must first check if the PendingIntent
exists and then you can create it to set/cancel it. To fix, do this:
In cancel button:
final Intent alarmintent = new Intent(AlarmActivity.this, AlarmReceiver.class);
final AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
// Determine if the alarm has already been set
boolean alarmUp = (PendingIntent.getBroadcast(AlarmActivity.this, 2,alarmintent,PendingIntent.FLAG_NO_CREATE) != null);
if (alarmUp) {
final PendingIntent sender1 = PendingIntent.getBroadcast(getApplicationContext(), 2, alarmintent, PendingIntent.FLAG_UPDATE_CURRENT);
...
In save button:
final Intent alarmintent = new Intent(AlarmActivity.this, AlarmReceiver.class);
final AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
// Determine if the alarm has already been set
boolean alarmUp = (PendingIntent.getBroadcast(AlarmActivity.this, 2, alarmintent, PendingIntent.FLAG_NO_CREATE) != null);
if (alarmUp) {
final PendingIntent sender1 = PendingIntent.getBroadcast(getApplicationContext(), 2, alarmintent, PendingIntent.FLAG_UPDATE_CURRENT);
...
EDITED again to fix documentation discrepancy with PendingIntent.FLAG_NO_CREATE
:
Note: It seems the Android documentation about PendingIntent.FLAG_NO_CREATE
is wrong! It says:
Flag indicating that if the described PendingIntent already exists, then simply return null instead of creating it.
but this is backwards. This method will return the PendingIntent
if it already exists. It will return null
if it doesn't already exist.
I've edited my answer to reflect the correct operation of this flag.