Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Android APP Development: Working with Services and Broadcast Receivers

See in this article how to use services and broadcast receivers in an Android app.

Mobile platforms support multitasking features, which enable simultaneous execution of multiple apps. Some of these apps require user intervention while others can run in the background without any user intervention. App components, which run in the background and perform specific tasks, are implemented in Android using services. Another useful app component is the broadcast receiver, which is used to inform all the concerned apps about the occurrence of an event, such as the arrival of an SMS. When an event occurs, the apps registered to receive the broadcasts are notified by the broadcast receivers.

Working with Services

While developing an Android app, you would require that a task, such as playing music, continues in the background while the user is playing a game or performing some other task. Such tasks are accomplished in Android apps by using services. A service is an app component that doesn’t have any UI and can perform long-running operations in the background. Services continue running in the background while the mobile device is being used for other activities or tasks.

They can be executed in a separate thread apart from the main thread and you can manage them from an app component, such as an activity. Therefore to interact with a service, you may need to create an activity. For example, you have a simple Rich Site Summary (RSS) reader with a list that includes all the new posts from a news website. A service will search for the updates by using the website, and then send those updates to a ViewNewsHeadlines activity. You can then create another activity, such as the ManageFeeds activity, to start or stop this service.

Forms of Services

Services are generally used for updating data sources and providing updates to the visible activities. In addition, services are used for triggering notifications, such as SMS or e-mail received notifications. Services are started, stopped, and controlled from other app components including other services, activities, and broadcast receivers. A service can essentially take the following two forms:

  • Started: A service is said to be in the started form when an app component, such as an activity, starts it by calling the startService() method. Once a service is started, it can run in the background for an indefinite period of time even if the component that started it is destroyed. Typically, a service that has been started performs a single operation and doesn’t return a result to the caller component. For example, a started service might upload a file over the network. When this operation is completed, the service would stop itself. Started services receive a higher priority than inactive or stopped activities making them less likely to be terminated by the Android's resource management system.
  • Bound: A service is said to be in the bound form when an app component, such as an activity, binds to it by calling the bindService()method. A bound service provides a client-server interface. This client-server interface allows app components to interact with the service, send requests, get results, and communicate across processes using IPC. A bound service can run till the time another app component is bound to it. More than one component can bind to the service at a time and when all the components unbind, the service is destroyed. Consider the example of a music player service. You may want to display the details of the currently playing song and also allow the user to select a song to be played. This can be done by binding the music playing service to an activity, where such details can be displayed. It is also possible to create a started service that can be bound to other app components. Such a service needs to be started, to run indefinitely, using the onStartCommand()callback method and during its lifetime, it can be bound to other components using the onBind()callback method of the android.app.Service class.

Note: When a service is started, it runs within the main thread of the app that started it unless explicitly specified to run in a separate thread. Therefore, if a service is going to perform tasks which would block the CPU, such as playing music, you should run it in a separate thread to minimize the chances of errors, such as Application Not Responding (ANR) error. This would also make the main thread of the app to be available at all times for user interaction.

Lifecycle of a Service

The lifecycle of a service can follow two different paths depending on the form of the service, which can be either started or bound. To understand the lifecycle of a service, consider the example of a media player service that starts when an activity starts a service to play a music file. During the lifetime of this service, another activity may bind to the same media player service to change the music file or maybe provide an interface to the user to start, pause, or stop the music. If the user chooses to stop the music, the media player service gets destroyed and releases all acquired resources.

Lifecycle of a Started Service

A service is started when a component, such as an activity calls the startService()method to invoke the service. Once the service is invoked, it runs indefinitely in the background until:

  • The service stops itself by calling the stopSelf()method.
  • Another app component stops the service by calling the stopService()method.

When a service is stopped, the system destroys that service. The following figure depicts the lifecycle of a started service.

The Lifecycle of a Started
Service

Figure 1: The Lifecycle of a Started Service

Lifecycle of a Bound Service

A bound service is created when another app component, such as an activity calls the bindService()method to bind with the service. Once the app component is bound with the service, it communicates with the service through the IBinder interface. The component can unbind from the service by calling the unbindService()method. A service can allow multiple components to bind with it, as evident from the preceding media player example. A service does not need to stop itself. It is automatically stopped and destroyed when all the components that are bound to it unbind themselves from it. The following figure depicts the lifecycle of a bound service.

The Lifecycle of a Bound
Service

Figure 2: The Lifecycle of a Bound Service

Starting a Service

A service can be started from an app component, such as an activity using the startService()method. This method takes an Intent object as a parameter, which contains the information about the service to be started, as shown in the following code snippet:

Intent i = new Intent(this, myService.class); startService(i); 

After the startService()method has been called by a component, the Android system checks if the service is running or not. If the service is already running, it calls the onStartCommand()method of the service, passing it the Intent object. In case the service is not running, the Android system calls the onCreate()method first and then the onStartCommand()method of the service. When multiple components start the service, the onStartCommand()method is called individually for each start request resulting in multiple calls to this method. In case of a bound service, the component that starts the service can create a PendingIntent object and pass it to the service. The service can then use this object to send a result back to the calling component.

Explicitly Stopping a Service

Since a service is an independent block of code, it needs to manage its own lifetime. This means that until the Android platform needs to recall the memory occupied by the service, the service will continue running in the background. A service needs to stop itself using the stopSelf()method, in case it is ideal for a long time. Alternatively, a service can be explicitly destroyed by another app component using the stopService(Intent iSrvce)method. iSrvce is the service's intent. Unlike the onStartCommand()method, only one call to the stopService()or stopSelf()method destroys the service.

To implement services in the Android apps, you need to:

  • Create a service by extending the android.app.Service class.
  • Register the service in the AndroidManifest.xml file.

Creating a Service

Services are created either explicitly or through an app component that requests to connect to the service. Since services are independent blocks of code that handle some requests for performing tasks, such as getting the latest updates from the Web or playing music in the background, they need to be created as a separate class. To create a service, you need to create a class by extending the Service class. In addition, you need to override some callback methods defined in the Service class. These callback methods handle various aspects related to the lifecycle of a service. In addition, they provide a mechanism for other components to connect with the service, if required. Some of the important callback methods that you can override are:

  • onStartCommand(): This method is called when another app component requests to start the service by calling the startService() method. After the execution of this method, the service is started and can run in the background indefinitely until the stopSelf()or stopService(Intent iSrvce)method is called. If you are creating a bound service, you do not need to implement this method. The signature of the onStartCommand()method is:
public int onStartCommand(Intent intent, int flags, int startId)

Where, intent is the intent that has been supplied to the startService()method and flags provides data about this start request. startId is an integer that uniquely identifies each start request.

  • onBind(): This method is called when another component requests to bind with the service by calling the bindService()method. Your implementation of the method should return an object of the type IBinder. This object allows the service to communicate with the calling component. The onBind()method should always be implemented. However, if the service does not allow binding, the method should return a null value. The signature of the onBind() method is:
public abstract IBinder onBind (Intent intent) 

Where, intent is the intent that has been supplied to the bindService()method.

  • onCreate(): This method is called when the service is first created. This method can include code to perform one-time setup operations. After the execution of this method, either the onStartCommand()or onBind()method is called. However, if the service is already running, this method is not called. The signature of the onCreate()method is:
  • public void onCreate()
  • onUnbind(): This method is called when all components bound to the service have been unbound by calling the unbindService()method. The signature of the onUnbind() method is:
public boolean onUnbind(Intent intent) 

Where, intent is the intent that has been supplied to the bindService()method.

  • onDestroy(): This method is called when the service is no longer being used and is being destroyed. This method can be used to include the code for performing clean-up operations, such as releasing resources. The signature of the onDestroy()method is:
public void onDestroy()

The following figure depicts the callback methods executed during the lifecycle of a started service.

The Callback Methods Executed
During the Lifecycle of a Started Service

Figure 3: The Callback Methods Executed During the Lifecycle of a Started Service.

The following figure depicts the callback methods executed during the lifecycle of a bound service.

The Callback Methods Executed
During the Lifecycle of a Bound Service

Figure 4: The Callback Methods Executed During the Lifecycle of a Bound Service

The following code snippet illustrates how to create a service and start/stop that service from another activity.

Below we can see the myActivity class that contains two buttons, Start Service button and stop Service button.

Listing 1: Creating a service and start/stop

package com.servicesDemo.example; 
  import android.app.Activity; 
  import android.content.Intent; 
  import android.os.Bundle; 
  import android.view.View; 
  import android.view.View.OnClickListener; 
  import android.widget.Button; 
  public class myActivity extends Activity 
  { 
  @Overrideprotected void onCreate(Bundle savedInstanceState) 
  { 
  super.onCreate(savedInstanceState); setContentView(R.layout.main);
  Button start = (Button) findViewById (R.id.button1); 
  start.setOnClickListener(new OnClickListener() 
  { 
  public void onClick(View view) 
  { 
  // Start the service defined in a separate class, myService.
  startService(new Intent (MyActivity.this, myService.class)); 
  }});
  Button stop = (Button) findViewById (R.id.button2); 
   
  stop.setOnClickListener(new OnClickListener() 
  {
  public void onClick(View v) { 
  // Stop the service started earlier.
  stopService(new Intent (MyActivity.this, myService.class)); 
  }});
   }
   }

Define a class for myService that will be started by an activity (myActivity). The following code provides the contents of the myService class:

Listing 2: myService Class

package com.servicesDemo.example; 
import android.app.Service; 
import android.content.Intent; 
import android.os.IBinder; 
import android.widget.Toast;
public class myService extends Service 
{ 
@Override public IBinder onBind(Intent arg0) 
{ 
return null; 
} 
boolean paused = false; 
@Override public void onCreate() 
{ 
super.onCreate();
Toast.makeText(this, "Service is created.", Toast.LENGTH_LONG).show(); 
paused = false;
Thread th = new Thread(new Runnable () { public void run() { 
// Call a method to perform a task .
some_task();
}
}
);
th.start();
} 
@Override public void onDestroy() 
{ 
super.onDestroy();
Toast.makeText(this, "Service being destroyed.", Toast.LENGTH_LONG).show ();
 paused = true;
}
private void some_task() 
{ 
for (int i = 0; i < 10; i++) 
{ 
// Ensure that the service is not paused. 
if (!paused) 
{
// Perform some task such as provide updates or play music. 
}} } } 

In the preceding code, when the app is executed, the main activity is displayed with two buttons. When the Start Service button is clicked, myService gets started and runs until the Stop Service button is clicked from the main activity.

The service keeps on running even if the main activity is closed and will keep on running till the main activity is executed again and the Stop Service button is clicked. The following figure displays the myActivity activity.

The myActivity Activity.

Figure 5: The myActivity Activity.

Registering a Service

You must declare all the services that you create in an app's AndroidManifest.xml file. To declare a service in the manifest file, you need to add a <service>element as a child element of the <application>element, as shown by the highlighted portion in the following markup:

Listing 3: Code to declare all the services in config file.

<application> 
           <activity android:name="myActivity" android:label="@string/app_name">
                <intent-filter>
                     <action android:name="android.intent.action.MA IN" /> 
                     <category android:name="android.intent.category. LAUNCHER" /> 
                </intent-filter> 
           </activity> 
   
           <service android:name=".myService"></ service> 
  </application>

There are several other attributes that you can include in the <service>element to define the properties of the service. For example, you can define a label for the service or an icon for the service. The highlighted portion in the following markup illustrates some of the attributes that you can include in the <service>element:

Listing 4: Config file updated

<application> 
       <activity android:name="myActivity"android:label="@string/ app_name"> 
           <intent-filter>
                <action android:name="android.intent.action.MA IN" /> 
                <category android:name="android.intent.category. LAUNCHER" /> 
           </intent-filter>
       </activity>
   
       <service android:name=".myService" android:label="test" android:icon="@drawable/icon"></service> 
  </application>

Note: Similar to an activity, you can declare an intent filter for a service.

Working with Broadcast Receivers

In an Android-enabled mobile device, messages called broadcasts are generated to inform any interested running apps about the occurrence of certain events. Broadcasts may be generated by:

  • The system: A broadcast generated by the system announces the system-level events, such as the screen is being turned off, the battery is low, or an SMS has arrived.
  • An app: A broadcast generated by an app announces the app-level events.

For example, an app that is downloading some data may want to inform other apps that the data has been downloaded and is available for use. Another example can be of an RSS news feeder app. By using this app, you may want to inform other apps whenever a new item is available. This can be done using a broadcast receiver, which enables other apps to register and receive a notification whenever a new feed is available. A broadcast is delivered in the form of intents. To receive and respond to a broadcast, an app needs to include a component called a broadcast receiver. Broadcast receivers do not provide a UI. However, they can create a status bar notification to alert the user when a broadcast is received.

Now this complete article shows how to manage the Services and Broadcast Receivers. I hope this article has clear all the conceptual complication in android service management. In Broadcast Receivers, there are two major types of broadcasts that can be received: (1) Normal Broadcasts, which are sent to all the interested receivers at the same time and the receivers run in an undefined order often at the same time. (2) Ordered Broadcasts, which are sent to all the interested receivers in a proper order, which means that a broadcast is delivered to one receiver at a time. When a receiver receives a broadcast, it can either propagate the broadcast to the next receiver or it can completely abort the broadcast so that it will not be passed to other receivers.

I am sure this article will help you a lot. Lots of new technologies are coming in my next articles. Watch this space for more.



Certified Trainer for Windows 8 Mobile App Development, IBM CE Project Trainer With IBM DB2, RAD, RSA, Certified Trainer for ZEND (PHP), Certified PHP and MySql trainer, Certified trainer of Diploma in Oracle 10g (DBA) as per Orac...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login