1

I have a background Android service. It runs in background, checks an URL for some results. And if results change, app sends a notification to user. I want this service to run every 3 hours. My problem is when and how to start the service ?

  • General behaviour is to create a Broadcast receiver.
  • Then start service when receiver gets a ACTION_BOOT_COMPLETED.
  • Also when receiver gets a boot completed, receiver will use AlarmManager and will create an alarm to run every 3 hours.

But after installing the application, what if the user doesn't restart his/her phone ? If user doesn't boot, AlarmManager won't create an alarm.

  • So another option is to create alarm when user first runs the application.
  • What if user restarts the application ? Should I cancel all previous alarms with AlarmManager.cancel and recreate the alarms ?

So in which conditions do you set alarms for your Android applications ?

trante
  • 33,518
  • 47
  • 192
  • 272
  • 1
    AFAIK, setting up an alarm for a given PendingIntent (based on a given Intent) cancels previous alarms for the same Intent. Give it a try. – Piovezan Oct 28 '13 at 20:04

1 Answers1

1

You have two ways to create the initial alarm, either when the app is started for the first time, or even better, have another broadcast receiver listening for ACTION_MY_PACKAGE_REPLACED. This is called whenever the app is installed or updated, and you can set up the alarm when that or a reboot happens (because a reboot clears alarms from the alarm manager). Then simply reset your alarm every time the service runs.

As an additional tip, check the Android WakeLock documentation in case you don't use them yet. Without setting a wake lock when the service is started, the phone might go to sleep right after the service's onStartCommand. And make sure resetting the alarm is done even if you run into some error situation (e.g. missing network connection) within the service.

Edit: Some people have had problems with ACTION_MY_PACKAGE_REPLACED. In these cases, ACTION_PACKAGE_REPLACED can be used as long as the code checks that it's the correct package that was replaced: ACTION_MY_PACKAGE_REPLACED not received

Community
  • 1
  • 1
J.Nieminen
  • 566
  • 5
  • 12
  • I get "ACTION_MY_PACKAGE_REPLACED" when I update my app. But it isn't triggered on new installations. – trante Nov 12 '13 at 20:43
  • "ACTION_PACKAGE_ADDED" doesn't always work for me. So it seems like I need to set alarms on ACTION_MY_PACKAGE_REPLACED, on ACTION_BOOT_COMPLETED. Also I need to set alarms on each run of my app, else my service won't be started until a reboot or app update. – trante Nov 12 '13 at 20:44