Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Service Class in Android

What is the purpose with Service class?

Many examples with Bluetooth Low Energy uses Service classes for all Bluetooth communication, connecting, disconnecting, scanning for devices etc. Activity classes always call method from this Service class.

What about implementing all Bluetooth communication directly in an Activity class instead?. Why does nobody implement like that and uses a Service class instead?

like image 684
user2521732 Avatar asked Sep 08 '26 09:09

user2521732


1 Answers

From the 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 loosly coupled component independet from activitys lifecylce. The problem is in Android you can't really control when an activity will be created/destroyed, so for example if you are loading somenthing in an activity and you receive a call, your activity might get destroyed and the result of your update will be lost, or even worst your loading task won't finish and holds on to the activity and it can't be garbage collected and you create a memory leak.

So you use service for long running background tasks, but you just let them run as long as you have to, to avoid, again, memory leaks and be nice to your resources.

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().

like image 172
Patrick Favre Avatar answered Sep 09 '26 23:09

Patrick Favre