Android Service Tutorial
What is an Android Service
An Android Service is a component used to perform operations in the background, these operations can be long indeterminate time operations. Unlike Android Activity and fragment, an android service does not have a user-facing interface. Android Service will continue to run in the background even if you switch to another application. You can also bind a component to a service to interact with it or use android service for IPC. Android Service is used in almost all popular apps that involve network requests, playing music in the background or perform download, upload saving of a file.
In this tutorial, we will use the most popular type of android service called IntentService. Android IntentService responds to intent. Any component that wants to start this service should send requests through startService(Intent). When IntentService receives an intent, it will launch a launch a worker thread which stops once it runs out of work.
Create the IntentService Example App
- Go to File → New → New Project and enter your Application Name.
- Enter company domain, this is used to uniquely identify your App’s package worldwide.
- Choose project location and minimum SDK and on the next screen choose Empty Activity, since we would be adding most of the code Ourselves. Then Click on Next.
- Choose an Activity Name. Make sure Generate Layout File check box is selected, Otherwise, we have to generate it ourselves. Then click on Finish. We have used the Activity Name as MainActivity since this will be the default screen when the user opens the app for the first time.
Gradle will configure your project and resolve the dependencies, Once it is complete proceed to next steps.
- Now open your project’s AndroidManifest.xml and add the following permissions.
Also, add an entry for the service that we will be creating under application tag.
This is the service that will poll the URL and get the Lucky Number.
Here, we are asking permissions for the Internet and accessing the network state.
Add the following code to the activity_main.xml
We are using a TextClock to show the system timing for the demonstration purpose. Android Service will run in background and get the data every minute.
Calling the Webservice from MainActivity
Open the MainActivity.java and add the following code.
We are invoking the service using the setServiceAlarm() method which we will discuss in a while.
Create Android IntentService class
First, we have defined the URL for getting the lucky number, Next we set the polling interval as 1 min. We have a newIntent() method to call our Android Service
When android service receives intent, it will start a background thread, and puts the intent on a queue. It will then service the intent using the onHandleIntent(Intent) on its background thread for each intent.
In the onHandleIntent(Intent), we are getting network availibility using the the isNetworkAvailableAndConnected method. For more details on how to check network availibility see
Checking an Internet Connection in Android Tutorial.
If the network is available, we are downloading the lucky number using Android Volley.
If the internet network is not available for the app or the device is offline, onHandleIntent(Intent) will return and won’t try to download the lucky number.
At the given URL, we are getting the number in a JSONArray as shown below.
Hence, we are deriving the number using the string “lucky_number” in the onResponse()listener of StringRequest method. We are using the singleton class AppSingleton.java to maintain a single request queue for the application.
Copy the code from AppSingleton.java ==> AppSingleton.java and add it your project.
Once we get the lucky number, we create a notification and to show the number in the Notification Area as shown in the image below.
To refresh the lucky number every minute, we need something to send the intent to android intent service on our behalf at an interval of 1 minute. This is done by AlarmManager – a system android service which can be used to send Intent. To inform the AlarmManager about the intent we want to send, we are using PendingIntent
We have added a static method setServiceAlarm(Context, boolean) in our Android service example code. We will invoke our android service by calling this method from the MainActivity.
In the setServiceAlarm(Context,boolean) we have created a PendingIntent object. Depending upon whether the alarm is currently on or off we will call AlarmManager.setInexactRepeating() method. We have to pass four parameters: a constant to describe the time basis for the alarm ,
the time to start the alarm, the time interval for repeating the alarm, and the PendingIntent to invoke once the alarm goes off.
We are using AlarmManager.ELAPSED_REALTIME for the time basis value, and start time in terms of elapsed realtime i.e SystemClock.elapsedRealtime() the alarm will go off once the specified POLL_INTERVAL elapses. We can also use a value of AlarmManager.RTC as the time basis, to base the time on actual wall time, if we want the alarm to go off at fixed point in time.
To cancel the alarm we use AlarmManager.cancel(PendingIntent) and then cancel the PendingIntent also.
Once you done with all the steps and run the Android service Example app. Now may also exit the app. You will see that our android service will keep rerunning in about every 60 seconds. You will notice that when our android service is invoked, a notification will be shown with the lucky number value retrieved from the URL.
What’s Next ??
After this simple Android Service Example Tutorial, Soon We will be covering articles covering more details on android services and how to use Broadcast and receiver in Android.
269 total views, 6 views today