4

I want to keep a service running in background, even when my app is killed. I'm using android.intent.action.USER_PRESENT event but the service only runs when the screen is unlocked. I tried android.intent.action.BOOT_COMPLETED but it needs to restarts the phone at least once after downloading the app.

Ideally I would start my service all X minutes, using ACTION_TIME_TICK for instance. Then check conditions (battery level, network connections...) before starting the service.

The problem is such event can't be declared and listened from manifest.xml but rather in an Activity, implying the app to be 'alive'.

Is there a way to do what I want anyway ?

ashoke
  • 6,441
  • 2
  • 26
  • 25
keepthepeach
  • 1,621
  • 2
  • 20
  • 27
  • 1
    try this http://stackoverflow.com/questions/15758980/android-service-need-to-run-alwaysnever-pause-or-stop I don – pcharb Oct 06 '14 at 04:48

1 Answers1

2

take a look at AlarmManager, which you can use to ensure your service is alive and well, if not, start/restart as needed.

You can register for AlarmManager the first time your app is opened after its installation. From then on, say if user reboots, register your service with AlarmManager using another (2nd) bootstrap service that listens to android.intent.action.BOOT_COMPLETED.

There may be other considerations with device sleep, and the amount/kind of work you do in your background service, take a look at this lib and notes as well

AlarmManager can continuously ensure your background service is healthy.

Community
  • 1
  • 1
ashoke
  • 6,441
  • 2
  • 26
  • 25
  • Thanks for comment but it seems that AlarmManager needs to be set from an activity as well. – keepthepeach Oct 06 '14 at 05:13
  • so you want a background service started immediately after a user installs your apk but doesn't start/open the app (there is no killing, yet) – ashoke Oct 06 '14 at 05:34
  • Ideally, yes. I don't mind if the user have to launch the app at least once but I'd like to start the service in background regularly even if killed, like I do with USER_PRESENT – keepthepeach Oct 06 '14 at 05:40
  • opened once, but on reboot, you want it to start automatically without any other actions or further opening. – ashoke Oct 06 '14 at 05:45
  • Yep, I know it isn't recommended but I'd like to. – keepthepeach Oct 06 '14 at 05:48