Fundamentals of Android services
Services are one of the core component in the Android system. if you want to show something in the Android screen we can use the activities (you can go to the my previous post about the activities) but what if you don’t need a screen what if you need to something out of sight out of mind in the Android UI so that’s where services comes in the picture. Best example for this is like playing music and download files in the background.
Most of Android developers know there is a two kinds of services, one is intentService another one is the normal service of-course there are more types of services. I will talk about types of services soon in this post. Intent service is most commonly used services because its inherent from Service class and most conman requirements are implemented in itself for us that’s why most of us use intentService
To use a services we should have intent object same like activity to start activity we need intent. In service case intents is called commands. (this is the reason that there is onStartCommand()
method in Service Class :) ) Each command is an instruction to the service to do the something depending upon the kind of service the command would be served in a variety of ways.
IntentService
First lets talk about the intentService, when you start the intentSservice this will create a background thread for us and what ever the task we provide to the intentService in execute in that background thread.
we can start the IntentService as we start the activities like startactivity(intent)
, but We can start the services using startService(intent)
by passing the intent. This intent are served by calling the onhandleIntent(Itent)
on its own background thread for each intent. Below code snippet of ExampleService
You can start InetentService
by calling
Intent i = ExampleService.newIntent(getActivity());
getActivity().startService(i);
If you are familiar with activities, all activities respond to the intents
, IntentService
also response to the intents
so must declare in your AndroidManifest.xml
file like below
<manifest ... >
...
<application ... >
<service android:name=".ExampleService" />
...
</application>
</manifest>
Services
Service is an application component that provides a life-cycle callbacks just like activity I.e call back or events performed on main thread for you but without UI.
Let’s dive into the services life-cycle.
onCreate()
— called when the service is createdonStartCommand(Intent, int,int)
— called once each time a component starts a service withstartService(intent)
onDestroy()
— called when the service is no longer needs to be alive.
Types of services
According to google developers guides
- Foreground Services — foreground service performs some operation that is not visible to the user for example I am using music app would be a foreground service to play audio track but user can interact with this service using the notification
- Background Services — a background service performs a long-term operation that is not directly noticed by the user
- Bound Services — I’ll talk about the bound services later in this post.
According to how services stick to your application
- Sticky Services — Sticky service is somewhere between regular service and foreground service Android will kill the process time to time of this service, however it will be created automatically if the resources are available as soon as possible.
onStartCommand
will be called on the next instance of the service with null intent instead of not being called at all. - Non-Sticky Services — Android system has less priority to the non sticky services it will not recreate the service again if the service is stopped due to out of memory and resources.
- Non-sticky Redeliver-Intent services — it is same as non sticky content but the only difference is it will re-deliver the same intent until it completes.
According to how services are bond to components
- Local binding services — a bound service allows components such as activities, broadcast receivers, content providers to bind to the service it will send request and receive the response.
- Remote binding Services — It is same as local binding service but the only difference is it is even perform inter process communication that i.e IPC. Most of the Android developers will not use this type of service, if you are familiar with Android open source project (AOSP) then you might used this kind of services
Sticky, Non-Sticky Services
Let’s talk about how services stick to the application componets. This type of services are determine what value returned from the onStartcommand()
method. Which maybe
- Service.START_STICKY
- Service.START_NOT_STICKY and
- Service.START_REDELIVER_INTENT
- Non-sticky services : START_NOT_STICKY services stops when the service itself says it is done. The name itself says non sticky so it will not stick to the your application once it is done. If you tell Android that you are done by calling either
stopSelf()
orstopSelf(int)
.stopSelf()
is unconditional so we will always stop the services no matter how many times you start it.stopSelf(int)
is conditional this methods take int value (startID
third parameter ofonStartCommand()
) received inonStartCommand()
this method will only stop your service if the this was the most recent start ID receive. This is howIntentService
works under the hood.
Let’s talk about the other type of START_NOT_STICKY services which is START_REDELIVER_INTENT the main difference between the START_NOT_STICKY and START_REDELIVER_INTENT is in how your services behave if the system needs to shut it down before it is done. START_NOT_STICKY service will die and disappear into the void but START_REDELIVER_INTENT on the other hand will attempt to start of the service again later when the resources or less constrained. Choosing between these two types is depending upon the operation how important trees if the service is not critical choose the START_NOT_STICKY.
- Sticky Services : The name itself says this service is stick to the application to make your service sticky you should return START_STICKY on the
onStartCommand
method. Sticky services is alive until the component calls oncontex.stopservice()
. Sticky services may be appropriate for the long running services like music player which needs to be stick around until user tells it to stop even then it is worth considering an alternative for architecture using non sticky services services management is inconvenient because it is difficult to tell whether the service is already started or not.
Bounded, Unbounded Services
Bound Services: It is possible to bind service by using bindService()
method. We call the methods inside the service directly by binding the services.
Note: We can’t bind a service from Broadcast receiver. The reason is broadcast receivers are light weight components, where it has to finish its functionality with in not more than 10 seconds maximum, whereas services are ment to deal with logrun operations. So android system does’t allow us to bind a service from broadcast recevers.
Bind services have additional lifecycle callbacks.
- onBind(intent) : called every time the service is bound and returns the IBinder object receive in serviceconnection.onserviceconnected() method.
- onUnbind(intent) : called when the service binding is terminated
serviceConnection
is an object that represents your service binding and receives all the binding callbacks to the Android components(Activiy, Providers) let’s see how it works in Activity. Not sure what is serviceConnection
? Its an interface that monitor the state of Service.
Lets see this serviceConnection callbacks in action.
With the above code, we create a connection between MainActivity
and MyService
. Also note we called a service method in MainActivity
Depending upon how is services bind we can differentiate this bound services in two types.
- Local services binding
If the service is local service then it may be a simple java object I.e iBinder in your local process. in the above code sample you can find LocalBinder
object which is used to get MyService
instance from Service class
- Remote services binding
If the service binding is remote that is in different processes that is called remote service binding. Android interface definition language is the best example of remote service binding. (AIDL) which is used for inter process communication. On Android one process cannot normally access the memory of other process, so so they need to decompose their objects into primitives that operating system can understand and Marshall the objects across the boundary for you. With AIDL marshalling will be handled by Android system. Interprocess communication is a huge subject which is mainly used in Android open source project AOSP. I will write a blog about it later
In the next article I will talk about the job schedulers, how we can replace the services with job scheduler for better performance and better resource management.
If you are expert in Services then do read below blog from MindOrks
Congratulations!! 😎 You made it to the end. And if you liked this 😍article, hit that clap button below 👏. It means a lot to me and it helps other people see the story.
I really appreciate any suggestions and questions.
Fellow me on twitter for updates !!!