Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice to use multiple background services in a single android app?

I'd like to keep some things separate from each other (in this case a 15-seconds interval task that polls a database, and a third party library that receives push notifications from our sip server). I'd like to keep them separate mainly to keep the code more readable, but I also think it's cleaner in general to keep separate tasks, you know, separated...
This said, is it bad practice to use multiple services for this? Is it perhaps better to use one service with multiple threads? Is it even possible to use more than one service?
I haven't really tried anything yet, I'm not eager to rewrite the code if it might be a bad thing to do.

like image 801
Kevin Avatar asked Aug 05 '13 07:08

Kevin


People also ask

What is the current recommended way to handle long running background tasks in Android?

Recommended solutionScheduling deferred work through WorkManager is the best way to handle tasks that don't need to run immediately but which ought to remain scheduled when the app closes or the device restarts.

What is restrict background activity?

Android 10 (API level 29) and higher place restrictions on when apps can start activities when the app is running in the background. These restrictions help minimize interruptions for the user and keep the user more in control of what's shown on their screen.

What is the difference between foreground and background services on Android?

A Background Service is a service that runs only when the app is running so it'll get terminated when the app is terminated. A Foreground Service is a service that stays alive even when the app is terminated. And a Bound Service is a service that runs only if the component it is bound to is still active.

Which method is called when app goes in background?

The onPause() and onResume() methods are called when the application is brought to the background and into the foreground again. However, they are also called when the application is started for the first time and before it is killed. You can read more in Activity.


1 Answers

First of all, a service does not imply that a separate thread is running, but I guess this is what you want to do. If you run several threads, there is no way of the AndroidOS to terminate them besides killing the whole Dalvik VM. And this means that you have no way of knowing when you are about to be terminated. If you have a service with a thread and use proper life-cycle management, i.e. kill the thread when Android notifies the service that it is about to stop it, then it is easy to maintain state.

Regarding your question: use several services with one thread each

like image 50
Kurt Huwig Avatar answered Oct 19 '22 22:10

Kurt Huwig