How to call receiver one a hour?
-
31-05-2021 - |
Domanda
Is it possible to call receiver only on start of every new hour? I have running service and I need to call receiver only when the time changes from for example: five o'clock to six o'clock, etc.? Is there any way how can I do it?
Soluzione
You will need to use an AlarmManager
. Then schedule the times you want it to notify you. Google for more examples.
UPDATE:
What you can do is wake it up at the next hour, at 8.00 if time is 7.30 . Then shedule it for an hourly wake up the next time it starts.
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR,c.get(Calendar.HOUR)+1);
c.getTimeInMillis(); // use this in alarmmanager for the first time, 60*60*1000 from next time
Altri suggerimenti
You can use a combination of GregorianCalendar and an AlarmManager for this. You basically add 1 hour to the current time and then round downwards to the nearest hour. See an example here:
long UPDATE_INTERVAL = 60 * 60 * 1000; // 1 hour in milliseconds.
Calendar c = new GregorianCalendar(); // Get current time
c.add(Calendar.HOUR_OF_DAY, 1); // Add one hour to the current time.
// Set minutes, second, millisecond to 0, such that we ensure that an update is done
// at the end of the hour.
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
final AlarmManager alarm = (AlarmManager) context.getSystemService(ALARM_SERVICE);
// Set an alarm, starting from the end of the current hour, every hour, to execute
// the update service.
// pIntent is the pending intent you would like activate.
alarm.setRepeating(AlarmManager.RTC, c.getTimeInMillis(), UPDATE_INTERVAL, pIntent);
I assume you know how to call the receiver.