Component - 2.Services

Services:
  • A service can run in the background to perform work even while the user is in a different application
  • Services are started, stopped, and controlled from other application components including other Services,Activities, and Broadcast Receivers.
  • Service is involved in any CPU intensive (such as MP3 playback) or blocking (such as networking) operations,should spawn its own thread to do that work.
  • Android platform has following services:
  1. Location Manager
  2. Media Controller
  3. Notification Manager
A service can essentially take two forms:
Started
A service is "started" when an application component (such as an activity) starts it by calling startService(). Once 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 might download or upload a file over the network. When the operation is done, the service should stop itself.
Bound
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). A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.

Creating service:
Following steps are involved in creating a Service:
1. Create a new class by extending android.app.Service base class.
2. Override the following methods
• OnCreate: This method is called by the system when the service is first created.
• OnStartCommand: This method is called by the system every time a client explicitly starts the service.
• OnDestroy: Called by the system to notify a Service that it is being removed. The service should clean up an resources it holds (threads, registered receivers, etc) at this point.

Service Lifecycle

The service lifecycle. The diagram on the left shows the lifecycle when the service is created with startService() and the diagram on the right shows the lifecycle when the service is created with bindService().

Components in Servie:
  • It is possible to bind to a running service and start the service if it is not already running.
  • While connected, it is possible to communicate with the service through an interface defined in AIDL (Android Interface Definition Language).




Comments

Post a Comment

Please post comments here:-)

Popular posts from this blog

Android Objective type Question and Answers

Android Questions and Answers for written exams

Core Java -----Question and Answers