Question :1 => I want to run a service from 9 AM to 4 PM daily. I plans two method.Which one is best?
Method 1: Inside Service:(This service initialized at on create of activity when first time application starts)
if (9 AM <=current time<=4 PM)
{
fetch data from server.
}
Method 2:
In Activity oncreate use Alarm manager and start a service based on the alarm manager.Then wake up next day and start service.
Which method is best?
Question :2 => How to find a service is running or not programmatically?
Write a BroadcastReciever to receive the ON_BOOT broadcast (you'll need to add appropriate permission and intent filter to your manifest). The BroadcastReceiver exists only to create a 9 am notification with the Alarm Manager. The scheduled alarm has a PendingIntent which will launch the service. Obviously, set the Alarm to repeat every 24 hours.
When launched, the service simply runs normally until 4 pm, at which point it stops itself.
The service's onStartCommand() method should return the appropriate flags to cause the system to restart it if it crashes or gets killed.
The only thing I can't figure out is how to auto-start the service the first time it's installed. Waiting for the device to be rebooted isn't very practical. When I write apps like this, they're typically combined with an Activity that has controls to start and stop the service.