• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Should I use a Timer or an Alarm manager?

GIR

Member
Hello,

I have a chunk of code in my app that needs to be executed on the 1/4 hour, every hour, but I'm unsure which method to use.

Thanks to google Im now aware that I can use either a Timer or the Alarm manager.

I found an alarm example, which I can modify to run my code every 15 minutes from the time my app starts running, but I'm stuck getting it to run *on* the quarter hour:

Code:
Intent myIntent = new Intent(AlarmndsActivity.this, MyAlarmService.class);
pendingIntent = PendingIntent.getService(AlarmndsActivity.this, 0, myIntent, 0);
                  
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
                  
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
whereas if I use my own timer I have to:
A) check if the minutes is either 0,15,30 or 45
B) test/set a flag to make sure the code is run only once per 15 minute period
C) prevent my app from sleeping and kill the battery.

Any guidance hugely appreciated,
GIR
 
Back
Top