Implementing services in Android?


Introduction

In many android applications we can see them perform some background tasks in it such as playing music in the background. Many music applications can play the song when the app is not open and play the music in the background. This task can be done with the help of services in android. In this article we will take a look on How to implement services in Android.

Implementation

We will be creating a simple application in which we will be displaying a text view for displaying the heading of the application. Then we will be creating two buttons, one button we will be using to start our audio service and another button we will be using to stop the audio service.

Step 1 : Creating a new project in Android Studio

Navigate to Android studio as shown in below screen. In the below screen click on New Project to create a new Android Studio Project.

After clicking on New Project you will get to see the below screen.

Inside this screen we have to simply select Empty Activity and click on Next. After clicking on next you will get to see the screen below.

Inside this screen we have to simply specify the project name. Then the package name will be generated automatically.

Note : Make sure to select the Language as Java.

After specifying all the details click on Finish to create a new Android studio project.

Once our project has been created we will get to see 2 files which are open i.e activity_main.xml and MainActivity.java file

Step 2 : Working with activity_main.xml

Navigate to activity_main.xml. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>activity_main.xml to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <!-- creating a text view on below line-->
   <TextView
       android:id="@+id/idTVHeading"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_centerInParent="true"
       android:layout_marginStart="20dp"
       android:layout_marginTop="20dp"
       android:layout_marginEnd="20dp"
       android:layout_marginBottom="20dp"
       android:padding="4dp"
       android:text="Implementing Services in Android"
       android:textAlignment="center"
       android:textColor="@color/black"
       android:textSize="20sp"
       android:textStyle="bold" />
   <!-- creating a button on below line -->
   <Button
       android:id="@+id/idBtnStartAudioService"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idTVHeading"
       android:layout_margin="15dp"
       android:text="Start Audio Service"
       android:textAllCaps="false" />
   <!-- creating a button on below line -->
   <Button
       android:id="@+id/idBtnStopAudioService"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idBtnStartAudioService"
       android:layout_margin="15dp"
       android:text="Stop Audio Service"
       android:textAllCaps="false" />
</RelativeLayout>

Explanation : In the above code we are creating a root layout as a Relative Layout. Inside this layout we are creating a text view which is used to display the heading of our application. After that we are creating two buttons which we will be using to start and stop our audio service.

Step 3 : Creating a new java class for our Audio Service

Navigate to app>java>your app’s package name>Right click on it>New>Java class and name it as AudioService and add below code to it. Comments are added in the code to get to know in detail.

package com.example.java_test_application;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.provider.Settings;
import androidx.annotation.Nullable;
public class AudioService extends Service {
   // creating variable for media player on below line.
   private MediaPlayer mediaPlayer;
   @Override
   public int onStartCommand(Intent intent, int flags, int startId) {
      // initializing variable for media player.
      mediaPlayer = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
      // setting looping for media player and starting it.
      mediaPlayer.setLooping(true);
      mediaPlayer.start();
      return START_STICKY;
   }
   @Override
   public void onDestroy() {
      super.onDestroy();
      // stopping the media player/
      mediaPlayer.stop();
   }
   @Nullable
   @Override
   public IBinder onBind(Intent intent) {
      return null;
   }
}

Explanation : In the above code we are extending our Audio Service class with the service class. In this class we are firstly creating a variable for the media player. Then we are creating a method for onStartCommand. In this method we are initializing our media player and starting it to play the default ringtone which is set to the device. Then we are creating an onDestory method which will stop the media player.

Step 4 : Adding the service in AndroidManifest.xml file

Navigate to app>AndroidManifest.xml file and add below permissions to it in application tag to read sms.

<!-- adding a service in manifest file -->
<service android:name=".AudioService" />

Step 5 : Working with MainActivity.java file

Navigate to MainActivity.java. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>MainActivity.java to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

package com.example.java_test_application;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
   // creating variables on below line for text view.
   private Button startAudioServiceBtn, stopAudioServiceBtn;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      // initializing variables on below line.
      startAudioServiceBtn = findViewById(R.id.idBtnStartAudioService);
      stopAudioServiceBtn = findViewById(R.id.idBtnStopAudioService);
      // adding click listeners on below line.
      startAudioServiceBtn.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            // on below line starting the service.
            startService(new Intent(MainActivity.this, AudioService.class));
            // displaying toast message on below line.
            Toast.makeText(MainActivity.this, "Audio Service Started..", Toast.LENGTH_SHORT).show();
         }
      });
      stopAudioServiceBtn.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            // on below line stopping the service.
            stopService(new Intent(MainActivity.this, AudioService.class));
            // displaying toast message on below line.
            Toast.makeText(MainActivity.this, "Audio Service Stopped..", Toast.LENGTH_SHORT).show();
         }
      });
   }
}

Explanation : In the above code firstly we are creating variables for our buttons. Now we will get to see the onCreate method. This is the default method of every android application. This method is called when the application view is created. Inside this method we are setting the content view i.e the layout file named activity_main.xml to set the UI from that file. Inside the onCreate method we are initializing the variables with the id which we have given in our activity_main.xml file. After that we are adding an on click listener for both buttons. For our first button we are calling a start service method to start our service. For the second button we are calling stop service to stop our service and passing an intent to it for AudioService to start and stop our service. Along with that we are displaying a toast message that service is started or stopped.

After adding the above code now we have to simply click on the green icon in the top bar to run our application on a mobile device.

Note − Make sure you are connected to your real device or emulator.

Output

Conclusion

In the above code we have taken a look on How to implement services in android along with an example.

Updated on: 09-May-2023

442 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements