Sunday, October 26, 2014

Android Service - A bird's eye view

A service is an application component representing either an application’s desire to perform a longer running operation while not interacting with the user or to supply functionality for other applications to use. Each service class must have a corresponding declaration in package’s manifest XML file AndroidManifest.xml. A service can be started with Context.startService or Context.bindService 

Services like other application objects run in the main thread of their hosting process. This means that if the service is going to do any CPU intensive tasks, or blocking operations such as MP3 playback or networking respectively, then the service should spawn its own thread in which to do that work. The IntentService class is available as a standard implementation of service that has its own thread where it schedule its work to be done. 

Starting a service is as simple as creating an intent and and calling startService method. 

Intent intent = new Intent(this,HelloService.class);
startService(intent);

This results in calling Service’s onStartCommand method. 
IF the service is not already running, it creates the service by calling onCreate method and then call the onStartCommand method. 
Inorder to communicate back to an Activity, the service can make use of Intent and the activity can be broadcast receiver of those intents. 

As an example, If a location checking service needs to run continuously in the background  and report when there is a significant location change, it can create a service and listen for the location changes in background. When the service finds that there is significant location change, it can update that information to the Activity by sending an intent like below 

intent = new Intent(BROADCAST_ACTION);
          intent.setAction("com.test.locationbroadcast");
  intent.putExtra("Latitude",location.getLatitude());
          intent.putExtra("Longitude",location.getLongitude());
          intent.putExtra("Provider",location.getProvider());

          sendBroadcast(intent);

References:
http://developer.android.com/guide/components/services.html

No comments:

Post a Comment