Search code examples
androidbackground-servicepermanent

How does one implement a background notification service in android when all services except for foreground ones get shut down after some time?


I would love to offer a background notification service(real-time) but can't find a way how to make it work since background services get stopped by system and when I restart them from a receiver I get an error.

I see that other apps have it, but I checked the running services and they don't have any services there. Do you think they do it in some short intervals to check for new notifications ?

Any advice would be helpful.


Solution

  • You have two choices:

    1:Foreground Service.

    You can keep a service running indefinitely, by promoting your service to a "foreground service". You can only become a foreground service by adding a Notification for the service to the notifications area. Presumably one which allows users to make your service go away. See Service.setForeground.

    1. Poll periodically using WorkManager and AlarmManager

    These APIs allow you to schedule periodic work when there is an active internet connection. The basic idea is that you would poll every few minutes to see whether there is stuff to be done.

    There are no other options. This is by design. There is no way to lurk in the background constantly without displaying a notification. Android OS developers have put a lot of work into making sure that there is no other way.