Reputation: 7031
I have a service that tracks the location of the user periodically. I want this service to run only during working hours, so I want it to start at 9h and to stop at 18h.
I'm starting the service with an AlarmManager
with this code
Intent syncIntent = new Intent(AlarmService.this, TrackingService.class);
PendingIntent pendingIntent = PendingIntent.getService(AlarmService.this, 0, syncIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.HOUR_OF_DAY, 9);
alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), 1000 * 60 * 60 * 24, pendingIntent);
What should i do to schedule an alarm to stop the service at 18h ?
Thanks
Upvotes: 1
Views: 902
Reputation: 7797
In the code you posted you can set a single alarm using set()
instead of setRepeating()
. Then in your broadcast receiver you can check current time when alarm is received. If it is withing business hours (9 to 6) then you set another single alarm in your receiver. If it is not between 9 am and 6 pm then you schedule an alarm to 9 am tomorrow.
Upvotes: 0
Reputation: 40203
Register a BroadcastReceiver
and create a PendingIntent
for it using getReceiver()
. In its onReceive()
method call stopService()
on the running Service
instance. Hope this helps.
Upvotes: 1