Question

I have created a repeat alarm in an activity, and I'm trying to delete this alarm in another activity. It just won't happen.

Creation code in A.activity

AlarmManager am = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    Log.i("location", String.valueOf(id));

    Intent notifyCycle = new Intent(this,NotifyCycleChange.class);
    notifyCycle.setData(Uri.parse("custom://" + id));
    notifyCycle.setAction(String.valueOf(id));
    notifyCycle.putExtra(DatabaseHelper.COLUMN_ROWID, id);
    notifyCycle.putExtra(DatabaseHelper.COLUMN_TITLE, titleText.getText().toString());
    notifyCycle.putExtra(DatabaseHelper.COLUMN_DESCRIPTION, "       Enter Description");
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),(int)id, notifyCycle, PendingIntent.FLAG_UPDATE_CURRENT);


    am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime()
            + 60*1000,timestore, pendingIntent);
    Log.i("At here", "successfully");

and the Cancel code in B.activity

 AlarmManager alarmManager = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);

            Intent notifyCycle = new Intent(context, NotifyCycleChange.class);
            notifyCycle.setData(Uri.parse("custom://" + id));
            notifyCycle.setAction(String.valueOf(id));
            PendingIntent pendingUpdateIntent = PendingIntent.getService(getApplicationContext(), (int) id, notifyCycle, PendingIntent.FLAG_UPDATE_CURRENT);



            Log.i("location", String.valueOf(id));
            // Cancel alarms
            try {
                alarmManager.cancel(pendingUpdateIntent);
            } catch (Exception e) {
                Log.e("TAG", "AlarmManager update was not canceled. " + e.toString());
            }

There are no errors and I have checked for matching for id's

Was it helpful?

Solution

You should create an similar PendingIntent used when scheduling the Alarm to cancel the repeat Alarm

When setting the alarm you have created PendingIntent as PendingIntent.getBroadcast but in when cancel its PendingIntent.getService . This is wrong

Create a similar intent to cancel the alarm

 Intent notifyCycle = new Intent(context, NotifyCycleChange.class);
 PendingIntent pendingUpdateIntent = PendingIntent.getBroadcast(getApplicationContext(), (int) id, notifyCycle, PendingIntent.FLAG_UPDATE_CURRENT);

And then , cancel the alarm

 AlarmManager alarmManager = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
 alarmManager.cancel(pendingUpdateIntent);

OTHER TIPS

When you create pending intents starting and canceling alarm, contexts must be the same. Please consider to create static method to get context so that you can call it from another activity.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top