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 OverflowVideos
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))..
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);
}
You could put the music player in a service. This would make it independent from the Activities and you would still be able to control the playback through intents.
Here are some code example about it: https://stackoverflow.com/a/8209975/2804473 The code below is written by Synxmax here at StackOverflow, and covered in the link above:
public class BackgroundSoundService extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.idil);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
}
public void onPause() {
}
@Override
public void onDestroy() {
player.stop();
player.release();
}
@Override
public void onLowMemory() {
}
}
@Override
public void onCreate (){
super.onCreate();
Player = MediaPlayer.create(this, R.raw.jingle);
mPlayer.setOnErrorListener(this);
if(mPlayer!= null)
{
mPlayer.setLooping(true);
mPlayer.setVolume(100,100);
}
mPlayer.setOnErrorListener(new OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int
extra){
onError(mPlayer, what, extra);
return true;
}
});
}
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.
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.
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();
}
}