Print this page

Services Tutorials: Part 1. A simple Service

  • Written by  Clive

Doing it in the background. Services Tutorials. Part 1: A Simple Service

Android simple service tutorial icon

Our tutorial app shows you how to use Services to:

  • use a simple Service to update a user’s score on a server
  • use a foreground Service to play music in the background

There are two parts to the tutorial: Part 1 shows you how to use a simple Service and Part 2 shows you how to use a foreground Service.

serviceTutOutlay

The basic outline of our tutorial app

Keeping it simple: A Simple Service Tutorial

If you haven't already done so, maybe you'd like to have a look at the article, All about Services.

Check out the screenshot of the main activity below. Pressing the Start Service button starts the simple Service.

The Service starts a worker thread which does the work. It updates the user’s score on a server. The thread can’t interact with the main thread directly so it uses a Handler to update a text view. The text view displays confirmation of the update.

Service Tutorial app screenshot

A simple Service used to update a user’s score on a server. A text view is updated to confirm success

Let’s start at the beginning: The Main Activity

The main activity has three buttons. 

Pressing buttons: The Buttons

The Start Service button

Pressing the Start Service button updates the text view, showing that we’re updating the score. It also puts the user’s data into an intent and starts the service, passing it the intent with the data.

Here’s the code for the button:

Service Tutorial app Start Service button

The button that starts the simple Service

Note the following:

  • buttonStartSimpleService – we get an instance of a button
  • findViewById – we get the button view identified by its id in the layout
  • setOnClickListener – register a listener that listens for when the button is clicked
  • onClick – executes when this button is clicked
  • setText – we set the text view to display that we’re busy updating the score
  • startIntent – we create a new Intent that we’ll use to start the Service. It’s passed two parameters:
    • the context
    • the Service that we want to start
  • putExtra – we use this method to add data (username, password & score) to the intent. We’ll be able to use this data when the Service starts. For more on putting data into intents, see Passing data between activities.
  • startService – starts the Service specified in the intent that we pass as a parameter. It remains running if it is already running
  • startService return – it returns a ComponentName object containing information about the Service that was started. Some useful information that you can get out of this object includes:
    • package name – com.example.services.services_app
    • class name – com.example.service.services_app.MySimpleService
    • short class name - .MySimpleService
The Stop Service button

To stop the Service, simply call stopService() and pass the same intent that you used to start the Service as a parameter. Here’s the code to stop the service. It’s inside the Stop Service button’s onClick method:

Service Tutorial Stop Service button

Use stopService() to stop the Service

Note the following:

  • stopIntent – we create an Intent. It’s identical to the intent that we used to start the Service. It has two parameters:
    • the context
    • the identity of the running Service that we want to stop
  • stopService – stops the Service identified by the intent passed as a parameter, if it’s running. Nothing happens if the Service is not running
  • setText – we set the text to display that the Service has been stopped
  • stopService return – returns true if the specified Service was stopped else it returns false
Start another activity: The Foreground Activity button

Pressing the third button starts the foreground activity where the music player controls are. We’ll cover this in the second tutorial where we show you how to use a foreground Service.

Here’s the code that’s executed when the button is pressed:

Service Tutorial start activity button

Use startActivity() to start the ForegroundActivity activity

Note the following:

  • intentForegroundActivity – we create a new intent that we’ll use to start the foreground activity. It’s passed two parameters:
    • the context
    • the activity that we want to start
  • startActivity – starts the activity that we’ve identified in the intent that we pass as a parameter

Here to serve: The Service class

The Service uses a thread to update a user’s score on a server. For more on threads, have a look at the Using Threads Tutorial.

If the update was successful then the thread sends a message to a Handler to update a text view.

Here’s the code for the Handler:

Services Tutorial Handler

The background thread sends a message to the Handler. The Handler updates the text view

Note the following:

  • handler – our Handler. It receives and processes the message from the worker thread. We use it to update the text view
  • handleMessage – receives and processes the message from the thread
  • msg – the handleMessage parameter. It is a Message object containing data sent by the thread
  • bundle – the data in the Message object is contained in a Bundle object. For more on Bundles, have a look at Passing data between activities
  • message – we get the String out of the bundle and assign it to our String, message
  • setText – we display the message String in the main activity's text view
Anything to declare? The manifest file

Before we forget, you have to declare the Service in the AndroidManifest.xml file:

Declare Service in AndroidManifest.xml file

Declare the Service in the AndroidManifest.xml file

Note the following:

  • name – this is the only attribute that you have to include in the <service> element. This is where we specify the class name of our Service

Starting the Service: onStartCommand

Pressing the Start Service button in the main activity starts the Service.

The onStartCommand is where everything happens so let’s look at that code:

Service Tutorial onStartCommand

onStartCommand is called each time the client calls startService() or there is a restart after the Service was killed by the system

Note the following:

  • onStartCommand is called by the system when you call startService or the Service restarts after being killed by the system. It runs on the main thread. It receives three parameters:
    • intent – the intent that you pass in your startService(intent) call
    • flags – generated by the system. It contains additional data about this start request
    • startId – generated by the system. A unique id representing this specific start request. Each time onStartCommand is executed, it generates a new startId for that specific start. You can use it in stopSelf(startId)
  • switch statement – for interest sake, I’ve used a switch statement to filter the flag parameter. We don’t use this information in this app. There are three possible flag values. These values are supplied by the system when onStartCommand is called. The flags supply additional information about the start request. You can use this information to customize your code. The possible values are:
    • START_FLAG_REDELIVERY – uses the original intent in a restart
    • START_FLAG_RETRY – it’s trying to retry starting the Service as the original attempt failed
    • 0 – this is the default normal start
  • Toast – we display a Toast message stating that the Service has started
  • startBackgroundThread – the Service runs in the main thread, so we start a separate, background thread to do the work and free up the main thread. We pass two parameters to the startBackgroundThread() method:
    • the intent that we used to start the Service. It contains extra data (username, password & score) that we will use in the thread (well, not really)
    • startId – the unique id for this Service start
  • return – the Service starts and returns a value representing how it should restart if it is killed. You choose this return value, depending on how you want the Service to restart
  • START_REDELIVER_INTENT – we’ve chosen that the Service must be scheduled for a restart if killed while started. It will use the original intent in the restart. It remains scheduled for the restart until stopSelf(startId) is called (passing the startId originally given by onStartCommand). It will only restart if there are still intents left to process (i.e. the intents passed in the startService() calls)

Get off the Highway: The Background Thread

The Service runs on the main thread. We don’t want to block the main thread so we do our work on a separate thread.

Service Tutorial backgroundThread() method

This method starts a background thread and stops the Service when it has finished its work

Note the following:

  • The method receives two parameters:
    • intent – it’s the same intent that we used to start the Service. We get the data out of the intent. This would be used to access the server to update the user’s score. We’re only simulating the update so we don’t use the data
    • startId – this is the id of the started Service which is generated when the onStartCommand is called. We use it in the LogCat to show which Service we’re dealing with. We also pass it on in the message we send to the Handler when we update the text view
  • intent.getStringExtra – we get the user name and password out of the intent
  • intent.getIntExtra – we get the score out of the intent
  • backgroundServiceThread – we create our background thread, passing a new Runnable as the parameter
  • run – this method executes when the thread starts
  • if statement – we use an if statement to test the result of executing the updateScore() method. If it’s true (the update succeeded) then we execute the remaining code
  • msg – a Message object which we get by calling obtainMessage()
  • bundle – a Bundle object into which we’ll put a String message. Have a look at the tutorial, Passing data between activities for more on bundles
  • putString – we put our string into the bundle. Here’s some more info on Strings, Did you know? Things about Strings!
  • setData – puts the bundle into the Message object
  • sendMessage - puts our message in the message queue which will be received and processed by our Handler
  • stopSelf(startId) – this stops the Service, passing the startId ensures that any remaining instances of startService that still needs processing to be done, will be completed. The Service will stop immediately if you don’t include the startId parameter
  • setPriority – we set the priority of this thread to a priority slightly lower than the main thread. This ensures that it won’t have much of an impact on the responsiveness of the main thread
  • Log – we print out a number of messages in the log for you to follow. For more on the Log, check out the article, Using Android’s Log class API to debug Android application code
  • Start – we start the thread to do the work of updating the score

The work: Updating the score

We’re using the Service to update the user’s score. The work is done on a background thread so we can continue using the app without its responsiveness being affected.

Normally the update would require a network connection to a server. We’re only pretending to do the update so there’s no network connection.

Here’s the code for updating the score:

Service Tutorial updateScore method

This method simulates updating the user’s score

Note the following:

  • This method simulates updating the user’s score to the server. It returns true to indicate success

Get rid of the evidence: onDestroy

The onDestroy() method is called by the system when the Service is no longer needed. This happens when we press the Stop Service button which calls stopService(). We clean up and release all resources here.

Here’s the code:

Service Tutorial onDestroy method

The Service stops and we release any resources for use elsewhere

Note the following:

  • We can’t explicitly stop a running thread. If our thread is still running when we stop the Service, we can interrupt it as above

I hope that you have found this tutorial helpful.

This tutorial was created using Android Studio. You can download the project files here Download icon