public class BackGroundMusic extends Service {
    MediaPlayer mediaPlayer;
    AudioManager audioManager;
    int volume;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        mediaPlayer = MediaPlayer.create(this, R.raw.tune);
        mediaPlayer.start();
        return super.onStartCommand(intent, flags, startId);
    }


    @Override
    public boolean stopService(Intent name) {

        return super.stopService(name);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mediaPlayer.stop();
        mediaPlayer.release();
        mediaPlayer = null;

    }
}

and if You need to play the music

startService(new Intent(MainActivity.this, BackGroundMusic.class))

if you want to stop the music

stopService(new Intent(MainActivity.this, BackGroundMusic.class)).. 
Answer from Mr.Popular on Stack Overflow
๐ŸŒ
Quora
quora.com โ€บ Is-there-an-Android-music-player-that-plays-always-in-the-background
Is there an Android music player that plays always in the background? - Quora
Answer: Tried some standalone players and none could do this, they only worked at the forefront. However, ES File Explorer built-in music player can play music in the background. It looks very basic but thatโ€™s deceiving because it can play ...
๐ŸŒ
Google Play
play.google.com โ€บ store โ€บ apps โ€บ details
Playback: background play - Apps on Google Play
Here are some of the key features that make Playback stand out: * Stream music and watching videos with ease, even when your screen is off or on the lock screen. * Multitask using a floating picture-in-picture mode while listening to your music video in the background, just like a music player or in a floating picture-in-picture mode * Access 100โ€™s music genres like Electronic, Soul, Hip-Hop, Reggae, Rhythm & blues, Disco, Jazz and much more * Save your music or videos to favourites to watch later at your convenience.
Rating: 4.3 โ€‹ - โ€‹ 28.7K votes
Top answer
1 of 2
7
public class BackGroundMusic extends Service {
    MediaPlayer mediaPlayer;
    AudioManager audioManager;
    int volume;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        mediaPlayer = MediaPlayer.create(this, R.raw.tune);
        mediaPlayer.start();
        return super.onStartCommand(intent, flags, startId);
    }


    @Override
    public boolean stopService(Intent name) {

        return super.stopService(name);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mediaPlayer.stop();
        mediaPlayer.release();
        mediaPlayer = null;

    }
}

and if You need to play the music

startService(new Intent(MainActivity.this, BackGroundMusic.class))

if you want to stop the music

stopService(new Intent(MainActivity.this, BackGroundMusic.class)).. 
2 of 2
2

1. Make Background service

package service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.annotation.Nullable;
import java.io.IOException;


public class BackgroundSoundService extends Service {

    MediaPlayer mPlayer = null;
    private final static int MAX_VOLUME = 100;
    Context context;
    AudioManager.OnAudioFocusChangeListener afChangeListener;


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        int musicflag = (int) intent.getExtras().get("songindex");
        if (musicflag == 1) {
            playMusic(R.raw.s1_pondambience);
        } else {
            playMusic(R.raw.s2_integrative_music);
        }
        return Service.START_REDELIVER_INTENT;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mPlayer != null) {
            try {
                mPlayer.stop();
                mPlayer.release();
            } finally {
                mPlayer = null;
            }
        }
    }

    public void onTaskRemoved(Intent rootIntent) {
        stopSelf();
    }

    /*
    * playmusic custom method for manage two different background sounds for application
    * */

    public void playMusic(int musicFile) {
        if (mPlayer != null) {
            if (mPlayer.isPlaying()) {
                try {
                    mPlayer.stop();
                    mPlayer.release();
                    mPlayer = MediaPlayer.create(this, musicFile);

                    AudioManager am = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
                    int result = am.requestAudioFocus(afChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

                    if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                        // Start playback.
                        mPlayer.setLooping(true);
                        final float volume = (float) (1 - (Math.log(MAX_VOLUME - 85) / Math.log(MAX_VOLUME)));
                        mPlayer.setVolume(volume, volume);
                        mPlayer.start();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    mPlayer = MediaPlayer.create(this, musicFile);

                    AudioManager am = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
                    int result = am.requestAudioFocus(afChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

                    if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                        // Start playback.
                        mPlayer.setLooping(true);
                        final float volume = (float) (1 - (Math.log(MAX_VOLUME - 85) / Math.log(MAX_VOLUME)));
                        mPlayer.setVolume(volume, volume);
                        mPlayer.prepare();
                        mPlayer.start();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        } else {
            try {
                mPlayer = MediaPlayer.create(this, musicFile);

                AudioManager am = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
                int result = am.requestAudioFocus(afChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

                if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                    // Start playback.
                    mPlayer.setLooping(true);
                    final float volume = (float) (1 - (Math.log(MAX_VOLUME - 85) / Math.log(MAX_VOLUME)));
                    mPlayer.setVolume(volume, volume);
                    mPlayer.start();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /*
    * MediaPlayer methods
    * */

    public void pauseMusic() {
        if (mPlayer.isPlaying()) {
            mPlayer.pause();
            length = mPlayer.getCurrentPosition();

        }
    }

    public void resumeMusic() {
        if (mPlayer.isPlaying() == false) {
            mPlayer.seekTo(length);
            mPlayer.start();
        }
    }

    public void stopMusic() {
        mPlayer.stop();
        mPlayer.release();
        mPlayer = null;
    }

    public boolean onError(MediaPlayer mp, int what, int extra) {
        if (mPlayer != null) {
            try {
                mPlayer.stop();
                mPlayer.release();
            } finally {
                mPlayer = null;
            }
        }
        return false;
    }

}

and start and stop service whenever you want.

2. To Start Service use below method

 private void startBackMusic() {
        Intent musicintent = new Intent(MenuActivity.this, BackgroundSoundService.class);
        musicintent.putExtra(EXTRA_SONGINDEX, 1);
        startService(musicintent);
    }

3. To Stop Service use below method

 private void stopBackMusic() {
          Intent musicintent = new Intent(MenuActivity.this, BackgroundSoundService.class);
            stopService(musicintent);
    }
๐ŸŒ
Android Developers
developer.android.com โ€บ camera & media dev center โ€บ play media in the background
Play media in the background | Android media | Android Developers
To do so, you embed the MediaPlayer in a MediaBrowserServiceCompat service and have it interact with a MediaBrowserCompat in another activity. Be cautious with implementing this client and server setup.
๐ŸŒ
Gadget Bridge
gadgetbridge.com โ€บ home โ€บ gadget bridge ace โ€บ top 6 ways to play audio or video in the background on...
Top 6 Ways to Play Audio or Video in the Background on Android (2024)
February 8, 2024 - Certain Android smartphones have a โ€˜background streamโ€™ feature which is natively built into the sidebar. You can use this feature to play YouTube videos in the background. The only catch is that you wonโ€™t be able to see the video in PiP mode. However, it is ideal for listening to music on the YouTube app.
๐ŸŒ
Softonic
en.softonic.com โ€บ downloads โ€บ background-music-for-android
Download Background Music For Android - Best Software & Apps
Download Background Music For Android. Free and safe download. Download the latest version of the top software, games, programs and apps in 2025.
๐ŸŒ
Android Developers
developer.android.com โ€บ camera & media dev center โ€บ background playback with a mediasessionservice
Background playback with a MediaSessionService | Android media | Android Developers
To enable background playback, you should contain the Player and MediaSession inside a separate Service. This allows the device to continue serving media even while your app is not in the foreground.
Find elsewhere
๐ŸŒ
Your Business
yourbusiness.azcentral.com โ€บ play-music-background-android-phone-9682.html
How to Play Music in the Background on an Android Phone | Your Business
November 21, 2017 - If you need to access the Music ... can also play music in the background using third-party music apps such as Pandora Internet Radio and Winamp....
๐ŸŒ
MakeUseOf
makeuseof.com โ€บ home โ€บ android โ€บ the 11 best offline music player apps for android
The 11 Best Offline Music Player Apps for Android
August 3, 2023 - Overall, if you can get past the bare-bones interface, it's a solid choice that won't let you down. ... jetAudio HD offers both free and premium versions of its Android music player.
๐ŸŒ
NoteBurner
noteburner.com โ€บ youtube-music-tips โ€บ play-youtube-music-in-background-without-premium.html
Solved! Play YouTube Music in Background without Premium | NoteBurner
After that, import YouTube Music to the native music player on your device, and start enjoying. YouTube Music is a free app for iOS and Android that lets you play music in the background only while you're a paid subscriber - YouTube Music Premium or YouTube Premium member.
๐ŸŒ
LG USA
lg.com โ€บ us โ€บ mobile-phones โ€บ VS950 โ€บ Userguide โ€บ entertainment_To_play_music_in_the_background_while_accessing_other_applications.html
To play music in the background while accessing other applications
From the Home screen, tap Apps > Music Player . Tap a song in your library to listen to it. Tap the Menu Key > Settings and checkmark the Show notification option so that the music controller is displayed on the Notifications panel. Tap Home Key . Tap Apps and tap the application you want to access.
๐ŸŒ
Reddit
reddit.com โ€บ r/music โ€บ is there a app where i can listen to music in the backround for free?
r/Music on Reddit: Is there a app where I can listen to music in the backround for free?
February 27, 2023 -

Pretty much every app I try either requires you to pay to listen, pay to chose specific songs, or pay to play music in the background. I don't mind ads I just want to listen to music without needing to be on the app.

๐ŸŒ
Chron.com
smallbusiness.chron.com โ€บ play-music-background-android-phone-45231.html
How to Play Music in the Background on an Android Phone
November 22, 2017 - How to Play Music in the Background on an Android Phone. Android smartphones provide you with the ability to multitask when using your device in a fast-paced business environment. Use your Android smartphone's native music application to play audio in the
Top answer
1 of 1
6

Try this command inside adb shell dumpsys media_session | grep -E "Media button session is.*userId=0"

It will output like this

blueline:/ $ dumpsys media_session | grep -E "Media button session is.*userId=0"
  Media button session is com.bsbportal.music/media_session (userId=0)

Here is a single liner command for getting the package name of app playing the audio

dumpsys media_session | grep -E "Media button session is.*userId=0" | sed "s/.*Media button session is//g" | cut -d'/' -f1 | xargs

blueline:/ $ dumpsys media_session | grep -E "Media button session is.*userId=0" | sed "s/.*Media button session is//g" | cut -d'/' -f1 | xargs
com.bsbportal.music
blueline:/ $ dumpsys media_session | grep -E "Media button session is.*userId=0" | sed "s/.*Media button session is//g" | cut -d'/' -f1 | xargs
com.google.android.youtube
blueline:/ $

If you've paused the Music playing apps then you would get the same above output.

If you really wanna confirm if the audio/music or some content is really being played then you can combine the above command with another one to check its playback state.

dumpsys media_session | grep -E "Media button session is.*userId=0" -A11 | grep "state=" | sed "s/.*{state=//g" | cut -d ',' -f1

Returns "3" for playing state and "2" for paused state.

blueline:/ $ dumpsys media_session | grep -E "Media button session is.*userId=0" -A11 | grep "state=" | sed "s/.*{state=//g" | cut -d ',' -f1
2
blueline:/ $

All my tests were done on Google Pixel 3 running on Android 12, the shell commands might return a different output on different Android versions so make sure to fine tune them. (Or revert back to me if you need any help)

๐ŸŒ
Fossbytes
fossbytes.com โ€บ home โ€บ more โ€บ list โ€บ 11 best music player apps for android in 2022
11 Best Music Player Apps For Android In 2022 - Fossbytes
May 13, 2022 - For people who download music from YouTube, this is probably the best free music player app for Android. In the Discover section, you will find a Music tab where you can play audio of YouTube videos. On top of that, you can keep on playing the music in the background which makes it a perfect ...
๐ŸŒ
Softonic
en.softonic.com โ€บ downloads โ€บ background-player
Download Background Player - Best Software & Apps
... Floating Popup Player for Android is the perfect application for watching movies or videos while doing other things. The application is made with theโ€ฆ ... Discover Music is an Android app developed by Imagesound Musicstyling, available for free. This app allows you to interact with the ...
Top answer
1 of 10
9

Create a separate class for handling several conditions

import android.content.Context;
import android.media.MediaPlayer;
import android.util.Log;

public class MusicManager {
    static final int MUSIC_PREVIOUS = -1;
    private static final String TAG = "MusicManager";
    static MediaPlayer mp;
    private static int currentMusic = -1;
    private static int previousMusic = -1;


    public static void start(Context context, int music) {
        start(context, music, false);
    }

    public static void start(Context context, int music, boolean force) {
        if (!force && currentMusic > -1) {
// already playing some music and not forced to change
            return;
        }

        if (music == MUSIC_PREVIOUS) {
            Log.d(TAG, "Using previous music [" + previousMusic + "]");
            music = previousMusic;
        }
        if (currentMusic == music) {
// already playing this music
            return;
        }
        if (currentMusic != -1) {
            previousMusic = currentMusic;
            Log.d(TAG, "Previous music was [" + previousMusic + "]");
// playing some other music, pause it and change
            pause();
        }
        currentMusic = music;
        Log.d(TAG, "Current music is now [" + currentMusic + "]");
        if (mp != null) {
            if (!mp.isPlaying()) {
                mp.start();
            }
        } else {
            mp = MediaPlayer.create(context, R.raw.backGroundMusic); //Ur BackGround Music
        }

        if (mp == null) {
            Log.e(TAG, "player was not created successfully");
        } else {
            try {
                mp.setLooping(true);
                mp.start();
            } catch (Exception e) {
                Log.e(TAG, e.getMessage(), e);
            }
        }
    }

    public static void pause() {
        if (mp != null) {
            if (mp.isPlaying()) {
                mp.pause();
            }
        }

// previousMusic should always be something valid
        if (currentMusic != -1) {
            {
                previousMusic = currentMusic;
                Log.d(TAG, "Previous music was [" + previousMusic + "]");
            }
            currentMusic = -1;
            Log.d(TAG, "Current music is now [" + currentMusic + "]");
        }
    }

    public static void release() {
        Log.d(TAG, "Releasing media players");
        try {
            if (mp != null) {
                if (mp.isPlaying()) {
                    mp.stop();
                }
                mp.release();
            }
        } catch (Exception e) {
            Log.e(TAG, e.getMessage(), e);
        }

        if (currentMusic != -1) {
            previousMusic = currentMusic;
            Log.d(TAG, "Previous music was [" + previousMusic + "]");
        }
        currentMusic = -1;
        Log.d(TAG, "Current music is now [" + currentMusic + "]");
    }
}

Then in your MainActivity define a global boolean variable and set it to true before setContentView(....) in onCreate() i.e

    boolean continueBGMusic;
    ....
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        continueBGMusic=true;
    setContentView(R.layout.activity_main);
    .....
    }

Then update onPause() as

    public void onPause()
        {
            super.onPause();
            if(!continueBGMusic)
                MusicManager.pause();
    }

and onResume() as

    public void onResume()
        {
            super.onResume();

                continueBGMusic=false;
                MusicManager.start(this,R.raw.backGroundMusic);
    }

Update all ur three activities with the boolean variable and the two methods.

2 of 10
4

If you have not very much activities, You can manage this task by adding boolean flags in activities, where you want music to be played.
When you stop one Activity these flags will show you, whether other Activities need your MediaPlayer

So in your main Activity:

public class MainActivity extends Activity {

    static MediaPlayer introPlayer;
    static boolean sActive;

    @Override
    protected void onResume() {

    // starting the player if it is not playing
        if (!introPlayer.isPlaying()) {
            introPlayer.start();
            introPlayer.setLooping(true);
        }

        // true when activity is active
        sActive = true;
        super.onResume();
    }

    @Override
    protected void onPause() {

        sActive = false;
        super.onPause();
    }

    @Override
    protected void onStop() {

        // before stoping mediaplayer checking whether it is not used by other          activities

        if (introPlayer.isPlaying()
                && !(Activity2.sActive || Activity3.sActive)) {
            introPlayer.pause();
        }

        super.onStop();

    }
}

Other activities:

public class Activity2 extends Activity {

    static boolean sActive;

    @Override
    protected void onPause() {
        sActive = false;

        super.onPause();
    }

    @Override
    protected void onStop() {

        // pausing the player in case of exiting from the app
        if (MainActivity.introPlayer.isPlaying() && !(MainActivity.sActive || Activity3.sActive)) {
            MainActivity.introPlayer.pause();
        }

        super.onStop();
    }

    @Override
    protected void onResume() {
        sActive = true;

        if (!MainActivity.introPlayer.isPlaying()) {
            MainActivity.introPlayer.start();
            MainActivity.introPlayer.setLooping(true);
        }

        super.onResume();
        }
}

And

public class Activity3 extends Activity {

    static boolean sActive;

    @Override
    protected void onPause() {
        sActive = false;

        super.onPause();
    }

    @Override
    protected void onStop() {

        // pausing the player in case of exiting from the app
        if (MainActivity.introPlayer.isPlaying() && !(MainActivity.sActive || Activity2.sActive)) {
            MainActivity.introPlayer.pause();
        }

        super.onStop();
    }

    @Override
    protected void onResume() {
        sActive = true;

        if (!MainActivity.introPlayer.isPlaying()) {
            MainActivity.introPlayer.start();
            MainActivity.introPlayer.setLooping(true);
        }

        super.onResume();
        }
}