5

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?

Ramprasad
  • 7,981
  • 20
  • 74
  • 135
  • Use Alarm Manager to start a service a t 9AM and which ends at 4PM. That AlarmManager should wake up next day at same time using the pending intent. Make sure that your application starts when device is rebooted. – Sahil Mahajan Mj Nov 17 '12 at 05:13

1 Answers1

1

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.

Edward Falk
  • 9,991
  • 11
  • 77
  • 112
  • So i need to add Alarm Manager in Boot time broadcast receiver instead of adding in Activity oncreate. If do like this,we need to reboot device to set alarm manager after Application installed. – Ramprasad Nov 17 '12 at 05:41
  • 1
    Activity onCreate() would be a better choice, actually, but if you want the service to automatically restart after a device reboot, you should do both. – Edward Falk Nov 18 '12 at 01:58