In this article we will discuss about different android services with examples. We will discuss about what is Service, different types of services like Bounded, Unbounded and IntentService and how to implement different services in android along with the different concepts involved in android services.
Android Service is an application component that can perform long-running operations in the background, and it does not provide a user interface. Another application component can start a service, and it continues 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 can handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background. This is basically a Base Class for all Services.By default, a service runs in the same process as the main thread of the application.
Therefore, you need to use asynchronous processing in the service to perform resource intensive tasks in the background. A commonly used pattern for a service implementation is to create and run a new Thread in the service to perform the processing in the background and then to terminate the service once it has finished the processing.
Bounded Service: Bounded service is used to perform background task in bound with another component.Bounded Service gets starts by calling
bindService().Bounded Service is unbind or destroyed by calling
unbindService(). Bound Service is dependent on the component in which it is started.
A service is bound when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with interprocess communication (IPC).
Step 1: create an empty project in Android Studio.
create a class BoundedService which extends Service class. As we know if you want to create a service we need to extend from service class.
Step 2:Next we override
onBind() method which we implement when we create our bound service.
Step 3:Now let's create the bound service by extending the binder class.
So, first of all, we will create a class inside our my service class which will be a public class and I will name it as
MyLocalBinder. And this class will extend from the binder class and in this class we want to do is to create a method which returns Boundedservice and the method name is
getService(). And what this is going to do is it is going to return an instance of Boundedservice.this.
Step 4:We need to override methods of ServiceConnection
android.content.ServiceConnection is an interface which is used to monitor the state of service. We need to override following methods.
This is called when service is connected to the application.
We will be following this step in the Mainactivity class.
Step 5:In this step we are going to bind the service and start service using this code:
Step 6:And finally we are going to unbind the service using this
Step 7:And finally declare your service in AndroidMenifest file.
Unbounded Service is used to perform long repetitive task. Unbound Service gets starts by calling
startService().Unbound Service is stopped or destroyed explicitly by calling
stopService().Unbound Service is independent of the component in which it is started.It is a kind of service which runs in the background indefinitely, even if the activity which started this service ends.
A service is started when an application component (such as an activity) calls
startService(). After it's started, a service can run in the background indefinitely, even if the component that started it is destroyed. Usually, a started service performs a single operation and does not return a result to the caller. For example, it can download or upload a file over the network. When the operation is complete, the service should stop itself.
Create a class UnBoundedService which extends Service class. As we know if you want to create a service we need to extend from service class.In your implementation, you must override some callback methods that handle key aspects of the service lifecycle and provide a mechanism that allows the components to bind to the service, if appropriate. These are the most important callback methods that you should override.
onStartCommand():The system invokes this method by calling
startService() when another component (such as an activity) requests that the service be started. When this method executes, the service is started and can run in the background indefinitely. If you implement this, it is your responsibility to stop the service when its work is complete by calling
stopService(). If you only want to provide binding, you don't need to implement this method.
So the Service might be terminated by the runtime incase there are too many processes running on the system or by a stopService() call. The second argument passed to onStartCommand() and the return value of onStartCommand() states what should happen after the Service is terminated, i.e., the restart behaviour. Let’s examine the different values:
START_STICKY: Service will be restarted if it gets terminated whether any requests are pending or not. The Intent of the earlier request passed (before termination) will not be resubmitted, instead null will be passed as Intent data. Hence use this option for Services that do not depend on Intent data to manage its state. All the pending requests are delivered with the START_FLAG_RETRY as the second argument (can also get using Intent.getFlags()).
START_NOT_STICKY: – Service is only restarted for pending requests. The Intent data specified while making the startService() calls will be passed.
START_REDELIVER_INTENT – Similar to START_STICKY and will receive both pending and started requests. The pending requests are delivered with the START_FLAG_RETRY flag set in the second argument whereas previously started requests are redelivered with the START_FLAG_REDELIVERY flag set. Also the original Intent is re-delivered.
onBind():The system invokes this method by calling bindService() when another component wants to bind with the service (such as to perform RPC). In your implementation of this method, you must provide an interface that clients use to communicate with the service by returning an IBinder. You must always implement this method; however, if you don't want to allow binding, you should return null.
onCreate():The system invokes this method to perform one-time setup procedures when the service is initially created (before it calls either onStartCommand() or onBind()). If the service is already running, this method is not called.
onDestroy():The system invokes this method when the service is no longer used and is being destroyed. Your service should implement this to clean up any resources such as threads, registered listeners, or receivers. This is the last call that the service receives.
Note:Declare your service in AndroidMenifest file.
IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.
This "work queue processor" pattern is commonly used to offload tasks from an application's main thread. The IntentService class exists to simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.
All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time.
Intent Service is used to perform one time task i.e when the task completes the service destroys itself .Intent Service gets starts by calling startService().IntentService Implicitly calls stopself() to destroy.Intent Service is independent of the component in which it is started.
Create a class MyIntentService which extends IntentService . You should add a constructor with the name of your service class. You will need to implement just one other method called onHandleIntent(). This method is where your processing occurs. Any data necessary for each processing request can be packaged in the intent extras, like so (imports, comments, exception handling removed for code clarity, see the code for details.
Note:At last, declare your service in AndroidMenifest file.
Following is the project structure.
Create a empty project in Android Studio.Create a class MainActivityactivity_main.xml
This activity is basically to interact with user.In this activity we call all three servicesMainActivity.java
I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section.
Contact us: firstname.lastname@example.org