I have added alarms in a project I am currently working on. They are working fine with all my conditions. Facing one small problem. I have added a one-shot alarm, I want it to fire on time, which is working fine and upon reaching its time it is opening an activity with values I am sending through intent. Problem is even after the alarm has been fired, the pending intent is called up again and which opens the activity with null values when I close that activity it again pops up as many times as I close it. The pending intent is not getting cancelled after it has fired at its designated time. Below is my code to set alarm.
public void setAlarm(int hours, int minutes,String AMPM, String alarmType,String message, String extraMessage)
{
Random rand = new Random();
int n = rand.nextInt(10000) + 1;
Log.e("HMA",hours+" "+minutes+" "+AMPM + " " + message + extraMessage);
// Toast.makeText(getApplicationContext(), "Alarm On",
// Toast.LENGTH_SHORT).show();
Calendar calendar = Calendar.getInstance();
// set selected time from timepicker to calendar
calendar.set(Calendar.HOUR_OF_DAY, hours);
calendar.set(Calendar.MINUTE,minutes);
calendar.set(Calendar.SECOND,00);
if(AMPM.equals("PM")) {
Log.e("PM","");
calendar.set(Calendar.AM_PM, Calendar.PM);
}
else
{
calendar.set(Calendar.AM_PM, Calendar.AM);
}
Intent myIntent = new Intent(this,
MyReceiver.class);
AlarmManager alarmManager;
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
myIntent.putExtra("alarmType",alarmType);
myIntent.putExtra("gifMessage",message);
myIntent.putExtra("extraMessage",extraMessage);
PendingIntent pendingIntent;
// A PendingIntent specifies an action to take in the
// future
pendingIntent = PendingIntent.getBroadcast(
this, n, myIntent, 0);
// set alarm time
if(Build.VERSION.SDK_INT<19) {
alarmManager.set(AlarmManager.RTC,
calendar.getTimeInMillis(), pendingIntent);
}
else if(Build.VERSION.SDK_INT>=19 && Build.VERSION.SDK_INT<=22)
{
alarmManager.setExact(AlarmManager.RTC,
calendar.getTimeInMillis(), pendingIntent);
}
else if(Build.VERSION.SDK_INT>=23)
{
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC,
calendar.getTimeInMillis(), pendingIntent);
}
}
I solved it using IntentService instead of Service and returning START_NOT_STICKY in onStartCommand.