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 🙂