I am developing an application in which we maintain a mqtt connection to the server to receive jobs from server in real-time. Currently we are using an approach in which we use a foreground service to keep the connection alive even when the app is killed. The problem is that the long running service drains battery so fast. And also I'm not sure how it is gonna react in devices from different vendors. For example in Xiaomi devices, if the auto-start setting is not enabled for the app, the service can not start in foreground when the application gets killed. I've solved this problem, but I'm not sure if it is going to work on all other versions of MIUI and other vendors. Beside I've read that newer android versions are going to use machine learning algorithms to put battery consuming applications to sleep. So I'm looking for another solution instead of foreground service. So I'm asking is it possible to implement this scenario with WorkManager? Is it a good idea to use WorkManager instead of foreground service? Is there a better solution for this?
1 Answers
Currently we are using an approach in which we use a foreground service to keep the connection alive even when the app is killed.
Android ensures that foreground Services keep running and if killed, starts them again soon. However it's required for foreground Services to post a sticky notification that for an always running background app, it may be annoying. There's another way! You can request Android to ignore battery optimizations for your app. Ignored battery optimizations apps are exempted from Android O+ background restrictions and can start normal Services (not foreground Services) at any time.
The problem is that the long running service drains battery so fast.
The Service doesn't drain the battery, it's the network activity that drains the battery. The network activity comes from the MQTT keepalive property. Also note that battery consumption depends heavily on the underlying network transport technology too. WiFi uses less power, but cellular networks use much more power. So, in order to maintain a reliable connection to the broker and also lower the battery usage, you should trade off the keepalive against battery usage. Here's a good article to tune the keepalive parameter:
So I'm asking is it possible to implement this scenario with WorkManager?
No, WorkManager jobs are one-shot jobs, Android schedules them and runs them at a particular time in the future. In the meantime, your app's process may be killed and the broker sends you a message, then you'll receive the message when your JobService starts again, so that's not real-time anymore, it's now polling not pushing.

- 28,539
- 11
- 83
- 129