Open menu with table of contents Services and Broadcast Receivers
Logo of Stuttgart Media University for light theme Logo of Stuttgart Media University for dark theme
Android Development

Services and Broadcast Receivers

Stuttgart Media University

1 Agenda

  • Framework Components Part V - Service
    • Service Lifecycle
    • System Services
    • Custom Service
  • Framework Components Part VI - BroadcastReceiver
    • System Broadcasts
    • Receiver Registration
    • Local Broadcasts

2 Service

  • A Service provides two main features:
    • A facility for the application to tell the system about something it wants to be doing in the background
      • Calls to Context.startService()
  • A facility for an application to expose some of its functionality to other applications
    • Calls to Context.bindService()
  • A Service is not a separate process
  • A Service is not a thread (unless you want it to be)

2.1 Service Lifecycle


2.2 System Services

  • Android provides a number of predefined system services
  • They are exposed via a specific Manager class
  • Use getSystemService() to gain access to the service, e.g.
    • POWER_SERVICE to get a PowerManager and control power management actions.
    • ALARM_SERVICE to get an AlarmManager and create intents at the time of your choosing.
    • NOTIFICATION_SERVICE to get a NotificationManager and inform the user via device notifications
    • LOCATION_SERVICE to get a LocationManager and receive for example location (e.g. GPS) updates.
    • ...

_For more services read the documentation of Context

2.3 Custom Service

  • A service needs to be declared in the AndroidManifest.xml

2.4 Custom Service

  • The implementing class must extend the Service class or one of its subclasses
public class MyService extends Service {

    public int onStartCommand(Intent intent, int flags, int startId) {
        //TODO do something useful
        return Service.START_NOT_STICKY;
    public IBinder onBind(Intent intent) {
        //TODO for communication return IBinder implementation
        return null;

2.5 Service Restart Options

Option Description
Service.START_STICKY Service is restarted, if it gets terminated. Intent data passed to the onStartCommand method is null. Used for services which manages their own state and do not depend on the Intent data.Service is not restarted. Used for services which are periodically triggered anyway. The service is only restarted, if the runtime has pending startService() calls since the service termination.
Service.START_NOT_STICKY Service is not restarted. Used for services which are periodically triggered anyway. The service is only restarted, if the runtime has pending startService() calls since the service termination.
Service.START_REDELIVER_INTENT Similar to Service.START_STICKY but the original Intent is re-delivered to the onStartCommand method.

2.6 Starting a Service

  • Use the startService() method to start the service from within your activity
// Create an explicit intent
Intent i= new Intent(context, MyService.class);

// if needed, add data to the intent
i.putExtra("Param1", "Data for the service");

2.7 Custom Service Example

  • Use IntentService for asynchronous single tasks in the background
public class ExampleService extends IntentService {

    public ExampleService() {

    protected void onHandleIntent(Intent intent) {
        int waitTime = (int) intent.getExtras().get("wait_time");
        // do work here, e.g. download file
        try {
            Thread.sleep(waitTime * 1000);
        } catch (InterruptedException e) {

    // ...

3 Broadcast Receiver

  • Specialized event Intent handlers (like a message mailbox)
  • Subscription to specific action strings (possibly multiple)
    • Action strings are defined by the system or developer.
    • System broadcasts: e.g. timezone changed, low battery, picture has been taken, user changed language preferences
    • Application broadcasts: e.g. finished download, data is ready ...

4 Broadcast Receiver

  • System Broadcast Examples
Event Description
Intent.ACTION_BOOT_COMPLETED Boot completed. Requires the android.permission.RECEIVE_BOOT_COMPLETED permission
Intent.ACTION_POWER_CONNECTED Power got connected to the device
Intent.ACTION_POWER_DISCONNECTED Power got disconnected from the device
Intent.ACTION_BATTERY_LOW Battery gets low, typically used to reduce activities in your app which consume power
Intent.ACTION_BATTERY_OKAY Battery status good again

5 Broadcast Receiver

  • To receive a Broadcast, extend the BroadcastReceiver class:
public class MyPhoneReceiver extends BroadcastReceiver {

    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,"Incoming phone call", Toast.LENGTH_LONG).show();

6 Broadcast Receiver

  • For System Broadcast, register your class via the AndroidManifest.xml
  • Use intent-filters to specify the intents that your receiver will react on, e.g.:
<receiver android:name="MyPhoneReceiver" >
  <action android:name="android.intent.action.PHONE_STATE" >
  • Or register the class dynamically via registerReceiver(Broadcast receiver, IntentFilter filter)
    • This is usually done for local (app internal) broadcasts (see next slides)
  • Always unregister your receiver using unregisterReceiver()

6.1 Local Broadcasts (Deprecated)

  • Use the LocalBroadcastManager to send messages within your application
    • This is faster and has no security issues
  • Register the receiver in your onResume() method, e.g.

Note: The usage of LocalBroadCastManager is not recommended. Modern ways suggest the usage of LiveData that follows the observable pattern.

public void onResume() {

  // Register mMessageReceiver to receive messages.
        .registerReceiver(mMessageReceiver, new IntentFilter("my-event"));

6.2 Local Broadcasts (Deprecated)

  • Implement the BroadcastReceiver as usual, e.g.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
  public void onReceive(Context context, Intent intent) {
    // Extract data included in the Intent
    String message = intent.getStringExtra("message");
    Log.d("receiver", "Got message: " + message);

6.3 Local Broadcasts (Deprecated)

  • Unregister the receiver in your onPause() method, e.g.
protected void onPause() {
  // Unregister since the activity is not visible

6.4 Local Broadcasts (Deprecated)

  • The LocalBroadCastManager class is part of AndroidX library
  • You might need to link it to your project first, if it is not already included
    • This is done in Android Studio in your Project Structure-Dependencies or in the file

6.5 Sending a Broadcast (Deprecated)

  • Sending a custom broadcast is done by using the method sendBroadcast(Intent intent), e.g.
Intent intent = new Intent();
  • Sending a custom local broadcast is done by using the method sendBroadcast(Intent intent) of the LocalBroadcastManager, e.g.
Intent intent = new Intent();

7 Android Assignment 3

8 Summary

  • Services can be used to do things in the background once (e.g. download a file) or to expose functionality to other apps (e.g. updating location information)
  • Broadcast Receivers are used either to listen to system events, events of other apps or local events of your own apps
    • Security issues occur when sending system wide broadcasts, better use LocalBroadcastManager to send app specific broadcast events

9 Recap Questions

  • When do you use a Service? Write down a few cases where you would use a Service.
  • Can a Service block the UI-Thread?
  • How would you communicate your Activity that your Service has finished executing a task?
  • When would you use system broadcasts and when local broadcasts?
  • Which software design pattern is used with the broadcasts on Android?