views:

88

answers:

2

I have a service that will monitor location changes daily. What I know so far that to start a service at boot, I have to follow the linked tutorial. This way I can get the service started at boot, but to save battery I need it only between 9am-9pm.

Question is pretty simple, so I will repeat:

How can I ensure a service is started at 9am and stopped 9pm every day?

+2  A: 

Use AlarmManager to set two alarms, each with a PendingIntent that will call startService() on your service, but with distinct action strings ('start', 'stop'). When onStart() of your service detects the 'stop' action Intent, it arranges for an orderly shutdown (e.g., stopSelf()).

This will fail if the user applies a task manager to you in Android 2.1 or earlier, since the technique they tend to use will wipe out your alarms (in addition to killing the service). In that case, the user is presumably voting for your service to not run, so you should try to accommodate the user's wishes.

CommonsWare
@CommonsWare Where do I set the AlarmManager, can it be done in the service I want to manage?
Pentium10
@Pentium10: you would initialize your alarms in your boot-time `BroadcastReceiver`, most likely.
CommonsWare
@CommonsWare that's probably not the best entry point, think the case when the app has just been installed (the receiver not yet been fired, no phone restart yet). Instead starting up the app will cause service start (as discussed in an earlier question). So what I see is, that when the service starts that is the point when I can setup the alarm? I am wrong?
Pentium10
@Pentium10: You are also welcome to set up your alarms on first run of the app after install/upgrade. You don't have a choice but to also do them at boot time, since alarms do not persist past a reboot.
CommonsWare
@CommonsWare I still see problems, if I just setup them in my activity. This is related with having activity starting the service, and on boot started service, no activity started yet this time. I told you the best would be to start from the service, as I am not sure if my activity will be started after boot, only the service is started.
Pentium10
@Pentium10: You will need to register your alarms in 3 places to cover all your scenarios (on install, on upgrade, on boot). None of these will conflict, as your existing alarms are gone after an upgrade or a reboot.
CommonsWare
A: 

CommonsWare is right. This is the best way. You are writing an application and you had better not to change anything out of the application. If you want to add a system service(on boot started service), you need to modify the BSP and add your service to systemserver.java. It's not recommended.CommonsWare's suggestion can do this work. As you said about the activity, you can start the activicy when you receive the boot broadcast. Then do what your want.....

levi