Service - Android
**What is Service? **
Service is an Android Component which performs long running tasks in background and does not provide a user interface.
Service will continue performing it's work, even if user decides to switch to the another Application.
Service can do following work:
Network Transactions
File Input - Output
Playing Music
Interaction with Content Provider and many more.
A service is started, when another application component like Activity calls a method startService(). It runs in background for indefinite time, even if the activity by whom service was called is destroyed.
By default, when service is started by a component, it doesn't return response to the caller upon performing certain task. Let's say; File Uploading / Downloading. When service has finished the task, it will simply stop itself.
A component can bind the service by calling "bindService()" method. A bounded service offers client - server interface. That means, user can send request, get response from the service and can process boundaries with IPC.
A bound service, runs as long as there is a component bounded with it. Multiple components can also be bounded to the same service. Once all of the unbind service is destroyed.
The Android System kills your service, when resources are needed to other activity. If that other activity is using your service, then it is obvious that your service won't be killed. If in case, your service gets killed it will be recovered when resources are available. If onStartCommand() returns START_STICKY.
Usually, service resides as the same thread as our application. If our service is doing intensive task, it may slow down our application performance. To avoid this start new thread inside the service.
If an activity wish to use bindService() method, it needs an object of ServiceConnection class. This object allow us to handle service related events such as onServiceConnected and onServiceDisconnected. If we pass the flag, Context.BIND_AUTO_CREATE, the service will start, if it is not already running.
Code to Bind the Service
Intent intent = new Intent(context, LocationService.class);
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
Code to Unbind the Service
unbindService(serviceConnection)
Remember, serviceConnection is an object of ServiceConnection class. Which is mandatory while binding the service.
Following are the methods, that can be used while service.
onStartCommand
onBind
onUnbind
onDestroy
onCreate