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 Overflowpublic 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);
}
Videos
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.
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.
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.