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 ...
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);
    }
🌐
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 9
26

If you want to play background music for your app only, then play it in a thread launched from your app/use AsyncTask class to do it for you.

The concept of services is to run in the background; By background, the meaning is usually when your app UI is NOT VISIBLE. True, it can be used just like you have (If you remember to stop it) but its just not right, and it consumes resources you shouldn't be using.

If you want to peform tasks on the background of your activity, use AsyncTask.

By the way, onStart is deprecated. When you do use services, implement onStartCommand.

UPDATE:

I think this code will work for you. Add this class (Enclosed in your activity class).

public class BackgroundSound extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        MediaPlayer player = MediaPlayer.create(YourActivity.this, R.raw.test_cbr); 
        player.setLooping(true); // Set looping 
        player.setVolume(1.0f, 1.0f); 
        player.start(); 

        return null;
    }

}

Now, in order to control the music, save your BackgroundSound object instead of creating it annonymously. Declare it as a field in your activity:

BackgroundSound mBackgroundSound = new BackgroundSound();

On your activity's onResume method, start it:

public void onResume() {
    super.onResume();
    mBackgroundSound.execute(null);
}

And on your activity's onPause method, stop it:

public void onPause() {
    super.onPause();
    mBackgroundSound.cancel(true);
}

This will work.

2 of 9
2

AsyncTasks are good just for very short clips, but if it is a music file you will face problems like:

  • You will not be able to stop/pause the music in middle. For me that is a real problem.

Here is few line from Android developers page about AsyncTasks

AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask.

So currently I am looking in to other options and update the answer once I find the solution.

🌐
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.
Find elsewhere
🌐
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.
🌐
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 ...