Service classes in Android
What is the purpose of the Service class?
Many Bluetooth low energy examples use service classes for all Bluetooth communication, connect, disconnect, scan devices, and so on. The Activity class always calls methods from that service class.
How about implementing all Bluetooth communication directly in the Activity class? Why doesn’t anyone implement it like that and instead use service classes?
From documentation :
A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service might handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.
Basically it is a loosely coupled component, independent of the activity lifecycle. The problem is that in Android you can’t really control when an activity is created/destroyed, so for example, if you load something in an activity and get a call, your activity may be destroyed and the result of the update will be lost, or worse, your loading task will not complete and keep the activity to garbage collect it, causing a memory leak.
So you can
use services for long-running background tasks, but you can let them run whenever you need them to avoid another memory leak and treat your resources well.
Caution: It’s important that your application stops its services when it’s done working, to avoid wasting system resources and consuming battery power. If necessary, other components can stop the service by calling stopService(). Even if you enable binding for the service, you must always stop the service yourself if it ever received a call to onStartCommand().