In this tutorial you will learn about the Android Services and its application with practical example.
Android Services
As we discussed in Core Building Block of Android that Service is long running Background Process which perform operation in background. Service does not provide User Interface. For Creation of Service we need to create Subclass of Service or we can also use existing Subclasses of Services. Let’s Briefly Discuss Service
Service can handle network transaction , interact with content provider, play music, perform I/O etc.
Three different types of service listed below :
Foreground, Background, Bound.
Foreground: Foreground service continue running even when user is not interacting with the app, It must display a status bar icon.
Background: It simply means running service in background, It is not directly noticed by the user
Bound : When an application component bound with service by calling bindService() , It called Bound Service. Bound service allows components to interact with the service, send request , receive result. It offers client-server interface.
Lifecycle of Service
A service has lifecycle callback methods, Let’s understand these callback methods one by one
by below diagram.
1. onStartCommand() : A service is started when calls startService() method, It runs in background indefinitely. It is stopped by stopService() method and stopSelf() method.
2. onBind() : The system calls this method when bindService() is called.
3. onUnbind() : All clients unbind or disconnected by calling this method.
4. onRebind() : This method is called by system when new clients are connected to the service.
5. onCreate() : This is one time setup procedure when the service is initially created. If the service already running so this method won’t be called.
6. onDestroy() : System calls this method when it is not in used or destroyed. This method should be implemented by the services for cleaning threads, receivers, registered listener etc.
The following code will guide you that how it use.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
package com.myapplication ; import android.app.Service; import android.content.Intent; import android.os.IBinder; public class ExampleService extends Service { int start; IBinder binder; boolean allowRebind; @Override public void onCreate() { // The service is being created } @Override public int onStartCommand(Intent intent, int flags, int startId) { return start; } @Override public IBinder onBind(Intent intent) { return binder; } @Override public boolean onUnbind(Intent intent) { return allowRebind; } @Override public void onRebind(Intent intent) { // A client is binding to the service with bindService(), // after onUnbind() has already been called } @Override public void onDestroy() { // The service is no longer used and is being destroyed } } |