Please explain an Android Service
. How does it differ from an Activity
? Does it depend on an application state such as running in the foreground/background?
An Android service is a component that is designed to do some work without a user interface. A service might download a file, play music, or apply a filter to an image. Services can also be used for interprocess communication (IPC) between Android applications.
For Android Developers, a Service is a component that runs on the background to perform long-running tasks. 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.
The lifecycle of service can follow two different paths: started or bound. Started. Bound.
From the Android Developer's SDK reference for Service:
A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.
It is very important to note
that services, like other application objects, run in the main thread of their hosting process. This means that, if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such as networking) operations, it should spawn its own thread in which to do that work.
This is in contrast to an activity which is best understood as something a user directly sees and interacts with (a UI.)
A service, as mentioned above, can be used for longer-running operations that will continue even if you have no foreground activity, but they can, and eventually will be killed by Android's lifecycle if left in the "background" state. If you need your service to continue running as a single instance without being killed and restarted, I would recommend placing startForeground(int id, Notification notification) in your Service's onCreate
method and stopForeground(boolean removeNotification) in your Service's onDestroy
method.
For example, I have an app that uses a foreground Service
to record accelerometer data all night while the android device is next to the user's body. Though it is not required to be active, I also have an Activity
that broadcast an Intent
to a BroadcastReceiver
inside the Service
which tells the Service
that it should also broadcast an Intent
with accelerometer data as extras to a BroadcastReceiver
inside the Activity
.
Code: SleepActivity SleepAccelerometerService
Good luck and let me know if you need any more information!
a Service is a context similar to Activity but has no GUI.
Important: A service doesn't run in a new thread!
Read about Service and also check out How to always run a service in the background?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With