Reputation: 423
I am using AlarmManager()
to fire Notification. I am setting it to fire at 10:30 AM of the morning and repeat at every 24 hours.
My code is as follow. I have tested yesterday and the problem is that It was repeated around 4-5 times in just next 2 hours. I am not understanding that what is the problem. I want to fire it only at 10:30 AM of the morning and repeat at only 24 hours.
Please help me solve the problem. I am calling this code on my app's Splash screen onCreate()
My Code :
Intent myIntent = new Intent(Splash.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(Splash.this,
0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar firingCal = Calendar.getInstance();
Calendar currentCal = Calendar.getInstance();
firingCal.set(Calendar.HOUR_OF_DAY, 10);
firingCal.set(Calendar.MINUTE, 30);
firingCal.set(Calendar.SECOND, 0);
long intendedTime = firingCal.getTimeInMillis();
long currentTime = currentCal.getTimeInMillis();
if (intendedTime >= currentTime) {
alarmManager.setRepeating(AlarmManager.RTC, intendedTime,
AlarmManager.INTERVAL_DAY, pendingIntent);
} else {
firingCal.add(Calendar.DAY_OF_MONTH, 1);
intendedTime = firingCal.getTimeInMillis();
alarmManager.setRepeating(AlarmManager.RTC, intendedTime,
AlarmManager.INTERVAL_DAY, pendingIntent);
}
Upvotes: 2
Views: 2897
Reputation: 1849
// Retrieve a PendingIntent that will perform a broadcast
Intent alarmIntent = new Intent(HomeContactActivity.this,
AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(
HomeContactActivity.this, 0, alarmIntent, 0);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
// Set the alarm to start at 10:00 AM
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 10);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
manager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 86400000,
pendingIntent); // for repeating in every 24 hours
Upvotes: 0
Reputation: 13808
You can use CommonsWare cwac-wakeful library. It has an inbuilt support to set alarms.
Upvotes: 3