Search code examples
androidservicebroadcastreceiver

Android - Run a service in background even when app is killed or device rebooted


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 ?


Solution

  • 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.