I have a service that will monitor location changes daily. What I know so far that to sta开发者_Go百科rt 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?
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 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.....
精彩评论