0

I'm trying to cancel broadcast at specific event

I have the following code to set the AlarmManager

 done.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i=new Intent(getApplicationContext(),NotificationReciever.class);  // go to NotificationReciever
            i.putExtra("id",getIntent().getStringExtra("id"));  //send id that same id own each item in database
            Toast.makeText(getBaseContext(),getIntent().getStringExtra("id"),Toast.LENGTH_SHORT).show();
            PendingIntent pendingIntent=PendingIntent.getBroadcast(getApplicationContext(),(int)id,
                    i,PendingIntent.FLAG_UPDATE_CURRENT);
            AlarmManager alarmManager= (AlarmManager) getSystemService(ALARM_SERVICE);
            alarmManager.set(AlarmManager.RTC_WAKEUP, calendar2.getTimeInMillis(),pendingIntent); //go to  other activity must be changed to proper notificaton
            Reminder.super.onBackPressed();
        }
    });

When I want to delete an AlarmManager ...

Intent i=new Intent(getApplicationContext(),NotificationReciever.class);
                        PendingIntent pendingIntent=PendingIntent.getBroadcast(getApplicationContext()
                                ,Integer.parseInt(notesData.getID())
                                ,i
                                ,PendingIntent.FLAG_UPDATE_CURRENT);
                        pendingIntent.cancel();
                        AlarmManager alarmManager= (AlarmManager) getSystemService(ALARM_SERVICE);
                        alarmManager.cancel(pendingIntent);

but it doesn't cancel the AlarmManager, what's the problem?

Sajal Narang
  • 397
  • 1
  • 14

1 Answers1

1

Looks like you misunderstood the Concept of AlarmManager and its working. I suggest you read Alarm Manager | Working with example

To answer your question - To delete a scheduled Alarm you need to delete the corresponding PendingIntent. Always keep note of two things while creating the PendingIntent

  • ID- This acts as the unique identifier
  • Flag - Flag defines the behavior of Pending Intent

To cancel the scheduled alarm from anywhere in the Application just define the PendingIntent again with the same request ID and FLAG_NO_CREATE

 PendingIntent pendingIntent=PendingIntent.getBroadcast(this,REQUEST_CODE,intent,PendingIntent.FLAG_NO_CREATE);

 if (pendingIntent!=null)
    alarmManager.cancel(pendingIntent);

With FLAG_NO_CREATE it will return null if the PendingIntent doesn't already exist. If it already exists it returns reference to the existing PendingIntent. With FLAG_NO_CREATE before cancelling you can also confirm if the alarm is already scheduled or not.

Irshad Kumail
  • 1,243
  • 11
  • 10