Reputation: 686
I have this code in my app
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 11);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.AM_PM,Calendar.AM);
//Debug!!!!!
//calendar.set(Calendar.SECOND, Calendar.SECOND+5);
Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY ,pendingIntent);
In theory it sets an alarm every day at 11:30 AM ,but practically it fires this alarm every time application starts , or when i return to the main activity. I want to display this alarm every day at this specific time
Upvotes: 0
Views: 953
Reputation: 81
Compare your system time to the alarm time..if alarm time is less than equal to system time receiver will work..but if not then nothing will happen...Follow this below link for details-Scheduled Notifications Triggers Every Time I Open App
Upvotes: 0
Reputation: 1
alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY ,pendingIntent);
Here The time when to repeat alarm is given by calendar.getTimeInMillis()
function.
this will take current time and alarm will fire.
Right..
Let say you want to fire alarm after few seconds then you have to give time in milliseconds as
calendar.getTimeInMillis() + 10000; //here 10000 is milliseconds
So what you need to do first calculate time in milliseconds when you want to fire alarm. lets say
interval = nnnnnnnn; // replace nnnnnn with your time interval in milliseconds
calendar.getTimeInMillis()+ interval;
alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis()+interval, AlarmManager.INTERVAL_DAY ,pendingIntent);
Done ... This way Im using in my app ... Try it .. It will work for U. If you need my code ... mailto:[email protected]
Upvotes: 0
Reputation: 1007658
This will fire immediately the current time is after 11:30am, because you are setting the Calendar
object to be in the past.
One solution is to compare your Calendar
with the current time (System.currentTimeMillis()
), and add a day if your Calendar
is in the past.
Upvotes: 3