Below is my code for setting repeat alarm for daily. Now i need to stop my alarm after 2 days. I tried to stop alarm after adding 2 days but it is not working . Please anyone help me.
Intent myIntent = new Intent(this, MyAlarmService.class);
pendingIntent = PendingIntent.getService(this, (int) System.currentTimeMillis(), myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hour1);
calendar.set(Calendar.MINUTE, min1);
calendar.set(Calendar.SECOND, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000, pendingIntent);
Toast.makeText(this, "Start Daily Alarm", Toast.LENGTH_LONG).show();
//trying to cancel after 2 days
// add days to current date using Calendar.add method
calendar.add(Calendar.DATE, 2);
pendingIntent = PendingIntent.getService(this, (int) System.currentTimeMillis(), myIntent, 0);
AlarmManager alarmManagerstop = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManagerstop.cancel(pendingIntent);
here you pass the System time in milisecond in the 2nd parameter.
as in the 2nd parameter was the request code was pass so you have to do something like this.
you have to keep this request code for each alarm you are set. Note if you pass this request code with same value then it’ll be override your alarm. so you have to pass the unique request code.
For stop the alarm same request code was needed to find that PendingIntent object and pass to the alarm.cancel method like this way
and as you used System milisecond that was change in every milisecond so that request code also change frequently. To use this milisecond you can store in any static variable after that you can use same value.