Android Background Music Service

play music with background service

I'm not sure what your onPause() and onStop() are meant to do. However when you start a service for the first time using Context.startService() the onCreate() method of the service is called and then onStartCommand() is called and later when you call startService() again only the onStartCommand() is called. So for whatever reason if you want to play the sound in a service and pause that in the very same service, you need to provide the service an Action that specifies the action you want to do.

So in your activity when you want to tell the service to play the sound:

String action = "PLAY";
Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
myService.setAction(action);
startService(myService);

and to pause the sound:

String action = "PAUSE";
Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
myService.setAction(action);
startService(myService);

and in the onStartCommand() method in your service:

if (intent.getAction().equals("PLAY")) {
// resume the sound
}
if (intent.getAction().equals("PAUSE")) {
// pause the sound
}

and when you really need to stop the service meaning Destroy the service, call context.stopService() and only then onDestroy() method is called and the service is really destroyed.

Android background music service

Do it without service

https://web.archive.org/web/20181116173307/http://www.rbgrn.net/content/307-light-racer-20-days-61-64-completion

If you are so serious about doing it with services using mediaplayer

Intent svc=new Intent(this, BackgroundSoundService.class);
startService(svc);

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() {

}
}

Please call this service in Manifest
Make sure there is no space at the end of the .BackgroundSoundService string

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

Change background music volume from activity to service

Well once you have the SeekBar and the OnSeekBarChangeListener being called as you change the SeekBar, the next major thing is communicating this from your activity to your service this change.

Have a look at the android docs Creating a bound service for the offical way to communicate between an Activity and Service using no 3rd party libraries.

HOWEVER

You could also use a 3rd party library like EventBus (which I'd recommend as it's much easier to use and implement in my opinion).

Here is an example using EventBus:

build.gradle:

dependencies {
implementation 'org.greenrobot:eventbus:3.2.0'
}

MediaVolumeEvent.java:

public class MediaVolumeEvent {
private int volume;

public MediaVolumeEvent(int volume) {
this.volume = volume;
}

public int getVolume() {
return volume;
}
}

PlaySound.java:

public class PlaySound extends Service {
@Override
public void onCreate() {
super.onCreate();
EventBus.getDefault().register(this);
}

@Override
public void onDestroy() {
EventBus.getDefault().unregister(this);
player.stop();
super.onDestroy();
}

@Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(MediaVolumeEvent event){
player.setVolume(event.getVolume(), event.getVolume());
}
}

In your activity inside the OnSeekBarChangeListener:

SeekBar seekBar= (SeekBar) findViewById(R.id.seekBar);
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}

@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
EventBus.getDefault().post(new MediaVolumeEvent(progress));
}
});

My background music service in Android app keeps on playing even when I close the app

In the onDestroy() method of your MainActivity you have to stop the service.

@Override
protected void onDestroy() {
super.onDestroy();
if(isMyServiceRunning(Background_music.class))
{
stopService(new Intent(this, Background_music.class));
}
}


private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}

Hope this helps you.

Background music Android

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.

background music doesn't stop if app is onStop Android

Judging by what you want you need a more fine grained control over the starting and stopping of your MediaPlayer object. An easy solution would be to add intent-filters and actions like so:

public class BackgroundMusicService extends Service {

public static final String ACTION_START_MUSIC = "package_name.action_start_music";
public static final String ACTION_STOP_MUSIC = "package_name.action_stop";

private MediaPlayer player;

public IBinder onBind(Intent arg0) {

return null;
}

@Override
public void onCreate() {
super.onCreate();

player = MediaPlayer.create(this, R.raw.game_music);
player.setLooping(true);
player.setVolume(10, 10);

}

public int onStartCommand(Intent intent, int flags, int startId) {
if(intent.getAction() != null){
switch (intent.getAction()){
case ACTION_START_MUSIC :
if(!player.isPlaying()){
player.start();
}
break;
case ACTION_STOP_MUSIC :
if(player.isPlaying()) {
player.stop();
}
break;
default: break;
}
}
return START_STICKY;
}



@Override
public void onDestroy() {
player.release();
}

@Override
public void onLowMemory() {

}
}

Update your manifest :

<service android:name=".BackgroundMusicService"
android:exported="false">
<intent-filter>
<action android:name="package_name.action_start_music" />
<action android:name="package_name.action_stop" />
</intent-filter>
</service>

To use:

startService(new Intent(BackgroundMusicService.ACTION_START_MUSIC));

startService(new Intent(BackgroundMusicService.ACTION_STOP_MUSIC));



Related Topics



Leave a reply



Submit