Monday, October 20, 2014

Android developer : how to cancel alarm

if your app create own alarm. how to cancel it ?
it's imposible to get alarm has been created (by name or by id).
this is a simple way to cancel alarm.
To cancel alarm you can use method AlarmManager.cancel(PENDING_INTENT)
Intent in create alarm and cancel alarm must be same.
there is some sample code.

when you create alarm :
 long nextAlarm = new Date().getTime();  
 Intent alarmIntent = new Intent(this, AlarmReceiver.class);  
 alarmIntent.putExtra(Constants.BundleKey.ALARM_TYPE_KEY, Constants.BundleKey.REPEAT_ALARM_VALUE);  
 PendingIntent pendingIntent = PendingIntent.getBroadcast(context,   
                               99, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);  
 AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);  
 alarmManager.set(AlarmManager.RTC_WAKEUP, nextAlarm, pendingIntent);  

when you cancel alarm :
 long nextAlarm = new Date().getTime();   
 Intent alarmIntent = new Intent(this, AlarmReceiver.class);   
 alarmIntent.putExtra(Constants.BundleKey.ALARM_TYPE_KEY, Constants.BundleKey.REPEAT_ALARM_VALUE);   
 PendingIntent pendingIntent = PendingIntent.getBroadcast(context,    
                 99, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);   
 AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);   
 alarmManager.cancel(pendingIntent);      

Intent in create and cancel alarm is same "Intent alarmIntent = new Intent(this, AlarmReceiver.class);"

Happy coding .
cheers :)

0 comments:

Post a Comment