Hey guys, in this post we will see a simple Android Service Example. But first lets understand what is an Android Service?
Table of Contents
What is Android Service?
Service is a process, but the special thing is about the service is it doesn’t need user interaction and it runs on background. I hope you can imagine some Android Services Examples now. Like Playing music in background. It is a long running process and it does not need user interaction. In this Android Service Example I will show you playing music in background.
Android Service Example in Video
- You can watch the following video to get a detailed explanation as well.
Basics of an Android Service
Creating a Service
To create service we will create a normal class extending the class Service. And we should override the following methods.
onStartCommand()
- This method is invoked when the service is started using the startService() method. We can call the method startService() from any activity and it will request the service to start.
onBind()
- If it is needed to bind the service with an activity this method is called. The service can result back something to the activity after binding. But if you do not want to bind the service with activity then you should return null on this method.
onCreate()
- This method is called when the service is created.
onDestroy()
- When the service is no longer used and destroyed this method is called by the system.
Defining it on Manifest
- You need to define your service in your AndroidManifest.xml file. It is very important.
1 2 3 | <service android:name=".YourService" /> |
- You need to put the above code inside application tag for every service.
Android Service Example
Now lets see a working Android Service Example.
Creating an Android Studio Project
- Again create a new android studio project.
Creating User Interface
- Once the project is loaded come inside activity_main.xml and create the following layout.
- For the above UI you can use the following xml code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="net.simplifiedcoding.androidserviceexample.MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:orientation="vertical"> <Button android:id="@+id/buttonStart" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:text="Start Service" /> <Button android:id="@+id/buttonStop" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:text="Stop Service" /> </LinearLayout> </RelativeLayout> |
- Now we will code the MainActivity.java as below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | package net.simplifiedcoding.androidserviceexample; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity implements View.OnClickListener { //button objects private Button buttonStart; private Button buttonStop; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //getting buttons from xml buttonStart = (Button) findViewById(R.id.buttonStart); buttonStop = (Button) findViewById(R.id.buttonStop); //attaching onclicklistener to buttons buttonStart.setOnClickListener(this); buttonStop.setOnClickListener(this); } @Override public void onClick(View view) { if (view == buttonStart) { //start the service here } else if (view == buttonStop) { //stop the service here } } } |
- Now we will create our service.
Creating Service
- To create a service you just need to create a new class extending Service. And also you need to override some methods.
- I have create the following class MyService.java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | package net.simplifiedcoding.androidserviceexample; import android.app.Service; import android.content.Intent; import android.media.MediaPlayer; import android.os.IBinder; import android.provider.Settings; import android.support.annotation.Nullable; /** * Created by Belal on 12/30/2016. */ public class MyService extends Service { //creating a mediaplayer object private MediaPlayer player; @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { //getting systems default ringtone player = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI); //setting loop play to true //this will make the ringtone continuously playing player.setLooping(true); //staring the player player.start(); //we have some options for service //start sticky means service will be explicity started and stopped return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); //stopping the player when service is destroyed player.stop(); } } |
- As you can see we are simply playing the default ringtone inside the onStartCommand() so when you start this service the default ringtone will start ringing on loop until you don’t stop the service.
Defining Service in Manifest
- Before starting the service we need to define it inside AndroidManifest.xml, so modify manifest file as below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="net.simplifiedcoding.androidserviceexample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- defining the service class here --> <service android:name=".MyService" /> </application> </manifest> |
- Now lets see how we can start and stop the service.
Starting and Stopping Service
- Again come inside MainActivity.java and modify it as below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | package net.simplifiedcoding.androidserviceexample; import android.content.Intent; import android.media.MediaPlayer; import android.provider.Settings; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity implements View.OnClickListener { //button objects private Button buttonStart; private Button buttonStop; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //getting buttons from xml buttonStart = (Button) findViewById(R.id.buttonStart); buttonStop = (Button) findViewById(R.id.buttonStop); //attaching onclicklistener to buttons buttonStart.setOnClickListener(this); buttonStop.setOnClickListener(this); } @Override public void onClick(View view) { if (view == buttonStart) { //starting service startService(new Intent(this, MyService.class)); } else if (view == buttonStop) { //stopping service stopService(new Intent(this, MyService.class)); } } } |
- Now you can run your project. When you will tap on Start Service ringtone will start ringing. And even if you close your application ringtone will keep ringing. Because it is playing with a Service that runs on background. To stop it you have to stop the service using Stop Service button.
So thats all for this Android Service Example guys. Please leave out your comments if having any queries or confusions. Thank You 🙂

Hi, my name is Belal Khan and I am a Google Developers Expert (GDE) for Android. The passion of teaching made me create this blog. If you are an Android Developer, or you are learning about Android Development, then I can help you a lot with Simplified Coding.
in my oppo A33f after closing the app from recent app manager the service has stopped the playing ringtone
It is maybe because you have not used the onBind() to bind the service with the main activity.
How do we do that?
use this START_NOT_STICKY instead of START_STICKY in the MyService.java file to avoid restart of the music even after the app gets terminated completely
I am trying to set a countdown timer in recyclerview as an item, but that problem is when I am moving to other page this time is starting from first. How can I get update time, Can you please help me
I am aslo having same issue will u find the solution for this
Thank you for this tutorial. I have been looking for this solution.. Very helpful
hi, I’m new to android development. will you please make a tutorial on how to send https GET request in the background (even if app closed) and show the data on notification or at least detailed example. I’m trying to do this for a while now, please?
You have to make a service that will keep running in background..
Please how can start music in launching application without pressing start
Thank you . Its working
One more Doubt :
How to check internet connection through service.
Eg : WiFi or Mobile Data is Connected but No Internet at present at the time or manage speed of the internet.
Hi, thanks for the explanation.
My question is why the app keeps stopping when the start button is pressed? (the music is playing ok)
Thanks again.
Working fine ! but when i close the app from RECENT APPS it will going stop sound. How do i resolve this ?
I’am using android nougat version.
Thanks.
Explain about START_NOT_STICKY and START_STICKY
Thanks a lot for making this tutorial.
Thanks again.
Thanks again.
Thanks 100 times.
Happy Coding 🙂
every 10mint later service will stop and then after 10 mint service should start automatically how could do that ?
In Oreo startService is Depricated. So Can you Please provide the workaround for Oreo with the same example.
Hi when i ran this script,app is crashing when i click on start play.How do i resolve this
I am getting unable to create media player:
how can i pause music ?