Android Service Tutorial With Example

Android Service is an important component of the android application. Service is an application or an application component which runs in the background. It does not need to communicate with the user or main UI thread. Service is used for long running operations in the background or such tasks which do not require any interaction with the user.

Service runs on the main thread same as an activity, therefore, service can freeze your activity and application can become non-responsive. Long running operations must be on a separate thread so that they can’t block the main thread and activity must remain responsive to the user.

Android Service Example – Implementation

Location Tracking application is one the example of Service which keeps sending user location to remote server at regular intervals without any interaction with the user

The most effective way of learning anything is to practically implement it in a project. In this Android service tutorial, we will create a sample project and implement the service component. We will send some device information such as Android version and Android ID. I will create a separate tutorial on getting user location.

Topics to be covered in this tutorial

  • Creating a service that runs in the background
  • Starting and Stopping a Service
  • Passing data to Service from Activity
  • Perform long running operations in a separate thread
  • Performing repeated tasks in a service using Timer class
  • Making Http calls using HttpURLConnection
  • Using AsyncTask

Download Source Code

Android Background Service Example

Creating a new Project

Create a new project in Android Studio having empty Activity and name it ServiceTutorial

Creating Service

Create a java file and name it LocationService and copy the below code. This is the basic syntax of a service. We create service by extending Service class.

  • onBind method allows us to bind an Activity to the service and also allows an Activity to access the members and methods of WeatherService class.
  • onStartCommand() method is called when we start the Service explicitly by startService() method. It returns START_STICKY constant that means Service will keep running until we don’t stop it explicitly.
  • onDestroy() method is called when we stop the service by calling stopService method.

Declaring Service in AndroidMenifest

Service must be declared in AndroidMenifest file. We also need to add Internet permission as shown in below code. Final code of AndroidMenifest.xml

Adding functionality into Service

We created a service but it is not doing anything. Now we will add some functionality to it by adding Timer and AsyncTask classes. The timer is used to call AsyncTask at regular intervals. AsyncTask will send the Http request on a separate thread. AsyncTask is the simplest way to perform background operations without handling threads and handler. Final code of service class is given below.

Getting data sent by the activity via Intent

We have used Timer class and its scheduleAtFixedRate() method to make the code execute within run method after every 60 seconds (60000 ms). It will call SendLocation() after every minute

Creating SendLocation subclass by extending AsyncTask class. AsyncTask is started via the execute() method and then onPreExecute(),doInBackground() and onPostExecute() are executed respectively.

CallServer() method sends a Http request to the server as per given URL and returns the server response as InputStream.

StreamToString() method of Network class convert the InputStream to String format

Below is the code of Network class. We have used HttpURLConnection and URL classes to perform network operations.

Now we will add some code in MainActivity class in order to start and stop service and other UI operations. Below is the complete code of MainActivity.java. We have two buttons to Start and Stop service.

Getting Android ID and Android version. This data will be sent to server.

Starting the service and passing data to service. Updating TextView.

Stoping the service explicitly and updating the TextView.

This is the simple layout of MainActivity having couple of Buttons and TextViews. Below is the complete code of activity_main.xml.

Run the application

Run the application in the emulator and have a look at the screenshot

android service tutorial

We are sending some data to get_location.php on the remote server. This script will get the data from URL and store it into mysql database. Below is the code of get_location.php. It is getting data via $_GET[] and passing to a function.

Video Demo

Check Also

asynctask kotlin example

Kotlin AsyncTask Tutorial with Example

Here is an example of implementing AsyncTask in Kotlin. I will create an Android application …