Pisti
Pisti

Reputation: 133

How to set an alarm on dynamic date and time?

Android 2.1

code:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, day);
cal.set(Calendar.HOUR, hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);

Intent intent = new Intent(this, AlarmReceiver.class);
intent.putExtra("message", header);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);

When I don’t set a date-time and just add a few seconds it works perfectly.

But when I do set a date & time (I get the data as an answer from a different activity), it doesn’t work and I tripple checked that the data I’m getting is the correct one.

Any advices on what I’m doing wrong?

Upvotes: 0

Views: 1343

Answers (1)

MKJParekh
MKJParekh

Reputation: 34301

I think this can be the only problem in your code as you said,

When i dont set a date & time and just add a few seconds it works perfectly.

You are getting different values in variable like month,date,year and setting them to Calendar object.

FYI :The calendar object take months as January = 0 and December = 11 ,

and i doubt you are getting them as Jan=1 and Dec=12, So you are unknownly setting date of next month in Alarm to trigger.

Check the value of month what you are getting and apply cal.set(Calendar.MONTH, month-1); and then it will work.


If you have written that Alarm code in loop then do take care to pass unique id each time in PendingIntent instead of one static value.

Upvotes: 3

Related Questions