Adam
Adam

Reputation: 2192

How to start AlarmManager on top of hour?

How to start AlarmManager on top of the nearest hour? For example when user click on button and time is 12:32, I want to start service at 13:00 and then repeat it each hour, I tried this code, but it doesn't work, it start AlarmManager only a hour later, so if time is 12:32 it starts service at 13:32.

Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, cal.get(Calendar.HOUR_OF_DAY)+1);

        AlarmManager alarm = (AlarmManager)myService.this.getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(myService.this, AlarmReceiver.class);
        PendingIntent pIntent = PendingIntent.getBroadcast(BatteryService.this, 0, i, 0);
        alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 1000*60*60, pIntent);

Upvotes: 1

Views: 1280

Answers (3)

Abdalrhman Elsayed
Abdalrhman Elsayed

Reputation: 95

you can use int hour = calendar.get(Calendar.HOUR_OF_DAY); to start you alarm then use

AlarmManager.INTERVAL_HOUR 

to repeat you alarm but Notice that the alarm will start now then will be repeated every hour

Upvotes: 0

Stefan
Stefan

Reputation: 4705

When you create the calendar instance its time is the current time. 12:32 in your example. Then you add one to hour of day. Now its 13:32. You need to set the minutes (and seconds) to 0:

cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);  // well ...

Upvotes: 5

jtt
jtt

Reputation: 13541

Try rounding it based on the minutes... Of course this would require getting the CURRENT time.

Upvotes: 0

Related Questions