Android Background Music Service

Posted by

Hello everyone this is Ajay Thakur from easytechsolutions.info and i am back with another useful post which will cover how to use background service in android to start and stop music !

           

So lets get started guys:-

Below are the steps you need to follow in order to start background service in android:-

Step 1:- First of all as always start android studio and open new project and name it whatever you want.

Step 2:- Next you need to make 1 Edit Text to fill time and 2 Buttons one for start service and another one for stop service.

Step 3: Let’s start with making layout of our android service app copy below code and paste it in your activity_main.xml

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/parentLayout"
    android:orientation="vertical"
    android:padding="10dp"
    tools:context="com.example.ajayhack.androidserviceexample.MainActivity">

    <EditText
        android:id="@+id/ET_songPlay"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:gravity="center"
        android:hint="Enter Time !"
        android:inputType="number"
        android:textColor="#000" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:orientation="horizontal">

        <Button
            android:id="@+id/BT_songPlay"
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="1"
            android:background="#ff00"
            android:text="Play Song !"
            android:textColor="#fff" />

        <Button
            android:id="@+id/BT_songStop"
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="1"
            android:background="#ff00"
            android:text="Stop Song !"
            android:layout_marginLeft="5dp"
            android:textColor="#fff" />
    </LinearLayout>

</LinearLayout>

Step 4:- Now we need to make a Android Service class in order to play around with services make a new class and name it MyService.java  and copy paste below code in it

MyService.java

package com.example.ajayhack.androidserviceexample;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.os.Vibrator;
import android.support.annotation.Nullable;

/**
 * Created by ajayhack on 14/2/18.
 */

public class MyService extends Service {

    MediaPlayer mediaPlayer;
    Vibrator v;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        mediaPlayer = MediaPlayer.create(this, R.raw.om_shanti_om);
        mediaPlayer.setLooping(false);
        v = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        if (v != null) {
            v.vibrate(10000);
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mediaPlayer.start();
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        v.cancel();
        mediaPlayer.stop();
    }
}

In the above code we are extending our MyService class with Service and implementing its method to start and stop our service , we are also using Vibrating effect while playing service and stop while stopping service.

Step 5:- Next we need to call MyService class methods in our MainActivity.java class below is the code you need to copy and paste in your MainActivity.java class

MainActivity.java

package com.example.ajayhack.androidserviceexample;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Vibrator;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    //Defining Variables to be used:-
    EditText ET_songPlay;
    Button BT_songPlay;
    Button BT_songStop;
    LinearLayout parentLayout;

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

        initialize();
    }

    public void initialize(){
        ET_songPlay = findViewById(R.id.ET_songPlay);
        BT_songPlay = findViewById(R.id.BT_songPlay);
        BT_songStop = findViewById(R.id.BT_songStop);
        parentLayout = findViewById(R.id.parentLayout);

        //Attaching onClick Event:-
        ET_songPlay.setOnClickListener(this);
        BT_songPlay.setOnClickListener(this);
        BT_songStop.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()){
            case R.id.BT_songPlay:
                callPlay();
                break;
            case R.id.BT_songStop:
                stopPlay();
                break;
        }
    }

    public  void callPlay(){
        int a = Integer.parseInt(ET_songPlay.getText().toString());
        Intent intent = new Intent(MainActivity.this , MyService.class);
        PendingIntent pendingIntent = PendingIntent.getService(MainActivity.this , 0 , intent , PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        if(alarmManager !=null) {
            alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
                    + (a * 1000), pendingIntent);

            Snackbar.make(parentLayout , "Song Play After "+a+" seconds !" , Snackbar.LENGTH_SHORT).show();
        }

    }

    public  void stopPlay(){
       stopService(new Intent(MainActivity.this , MyService.class));
    }
}

Although we can simply start and stop service by calling it directly through intent from MainActivity class but we are using Pending Intent to start our service so that when we put time in Edit Text field it will start the service after the time we put inside our app Edit Text field ( by default time is count in seconds )

Step 6:- Last step is to register service class in manifest and also adding Vibrating permission

Manifest.xml

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

    <uses-permission android:name="android.permission.VIBRATE" />
    <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>

        <service
            android:name=".MyService"
            android:enabled="true" />
    </application>

</manifest>

in order to use service we need to register service inside our Manifest file so that when we request to start and stop service it will work smooth !

Thank You to all & Happy Coding !

Hope you get some useful information about android background service to play and stop music

Leave a Reply

Your email address will not be published. Required fields are marked *