Android Service Sample code for Playing Music on Background
Android Sample Codes

Android Service Sample code for Playing Music on Background

What is Android Service?

Android Service is a process runs on background indefinitely, but the special thing is about the android service is it doesn’t need user interaction. Android Services examples are like playing music in background. It is a long running process in the background.

In this Android Service Sample code for Playing Music on Background tutorial will show you playing music in background.

Before proceed you should have go through the life cycle methods of android service.

Basics of an Android Service

Android service is an application component that is used to perform operations in the background such playing music, perform network operations etc.

The service runs in the background even if the activity or application is destroyed. Before proceed you should have go through the life cycle methods of android service. Please visit this link to learn about the life cycle methods of android service.

Creating a Service

To create android service we will create a normal java class extending the class android Service. And we should override the following methods onStartCommand() or onStart(), onBind(), onCreate(), onDestroy().

Defining android Service on Manifest

It is very important to define your service in your AndroidManifest.xml file as shown below.

<service android:name=".YourService" />

 You need to put the above code inside application tag for every service.

Android Service Sample code for Playing Music on Background

 Now let’s see a working Android Service sample code for playing music.

Creating an Android Studio Project

Create a new android studio project by selecting empty activity. Here I have created a layout containing three Button: one for starting the service , one for stopping the service and the last one for displaying another activity.

Creating User Interface

Once the project is loaded come inside activity_main.xml and create the following layout.

Android Service Sample code for Playing Music on Background

For the above UI you can use the following xml code.

activity_main.xml

 <?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">


    <Button
        android:id="@+id/buttonStart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="74dp"
        android:text="Click Here To Start Service" />

    <Button
        android:id="@+id/buttonStop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Click Here To Stop Service" />

    <Button
        android:id="@+id/buttonNext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="63dp"
        android:text="Another Activity" />
</RelativeLayout>

Now we will code the MainActivity.java as below.

MainActivity.java

 package com.example.serviceexample;

import android.app.Activity;
import android.content.Intent;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity implements View.OnClickListener {
    Button buttonStart, buttonStop,buttonNext;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        buttonStart = findViewById(R.id.buttonStart);
        buttonStop = findViewById(R.id.buttonStop);
        buttonNext =  findViewById(R.id.buttonNext);

        buttonStart.setOnClickListener(this);
        buttonStop.setOnClickListener(this);
        buttonNext.setOnClickListener(this);


    }
    public void onClick(View src) {
        switch (src.getId()) {
            case R.id.buttonStart:

                startService(new Intent(this, MyService.class));
                break;
            case R.id.buttonStop:
                stopService(new Intent(this, MyService.class));
                break;
            case R.id.buttonNext:
                Intent intent=new Intent(this,AnotherPage.class);
                startActivity(intent);
                break;
        }
    }
}

Next we will create our service for playing music on background.

Creating Service

To create an android service you just need to create a new java class extending the built-in class Service and also override some methods that we discussed already.

Here I just created a java class named MyService.java.

MyService.java

package com.example.serviceexample;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.provider.Settings;

import android.widget.Toast;

public class MyService extends Service {
    MediaPlayer myPlayer;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {
        Toast.makeText(this, "Service Successfully Created", Toast.LENGTH_LONG).show();

        myPlayer = MediaPlayer.create(this,R.raw.sisira);
         //setting loop play to true
        //this will make the ringtone continuously playing        myPlayer.setLooping(false); // Set looping
    }
    @Override
    public void onStart(Intent intent, int startid) {
        Toast.makeText(this, "Service Started and Playing Music", Toast.LENGTH_LONG).show();
        myPlayer.start();
    }
    @Override
    public void onDestroy() {
        Toast.makeText(this, "Service Stopped and Music Stopped", Toast.LENGTH_LONG).show();
        myPlayer.stop();
    }
}

As you can see in the above code, before creating MediaPlayer object create a folder named raw by right clicking on the res folder that appears on the left panel of android studio.

Android Service Sample code for Playing Music on Background

Copy any mp3 file you have in your system and paste it on the raw folder by right click on it that you have created just now and give a name to it. Here I have gave a name as sisira.

myPlayer = MediaPlayer.create(this,R.raw.sisira);

Defining Service in Manifest

Modify manifest file before starting the service, You need to define it inside AndroidManifest.xml as below.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.serviceexample">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        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>
        <activity android:name=".AnotherPage"></activity>
        <service android:name=".MyService"
            />
    </application>

</manifest>

Use of Third Button

We have created already three button in the layout activity_main.xml, first button created for starting service and second button for stopping service. The third button created for displaying an activity.

Create new java class named AnotherPage.java and its corresponding layout named activity_another_page.xml by right click on the app folder appears on the left panel of android studio and selects the empty activity (app->New->Activity->Empty Activity).

Modify both files AnotherPage.java, activity_another_page.xml  as shown below.

AnotherPage.java

 package com.example.serviceexample;

import android.app.Activity;

import android.os.Bundle;

public class AnotherPage extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_another_page);
    }
}

activity_another_page.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
   <TextView
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:text="http://codeunplug.com"
       android:textSize="20dp"
       style="@style/Base.ThemeOverlay.AppCompat.Light"
       android:layout_gravity="center_horizontal"
       android:gravity="center"
       android:textColor="@color/colorAccent"/>
</LinearLayout>

Starting and Stopping Service

Now you can run your service project by click on run app (Shift+F10). When you will tap on “Click Here To Start Service” music will start playing. If  you close your application you can see ringtone will keep ringing since it is playing with a Service that runs on background. To stop it you have to stop the service using “Click Here To Stop Service” button.

Android Service Sample code for Playing Music on Background

One Reply to “Android Service Sample code for Playing Music on Background

Leave a Reply

Your email address will not be published.