Background music Android

Zookey picture Zookey · Oct 28, 2011 · Viewed 45k times · Source

Okey, this is my problem. I have one service class where Ive managed to create media player to play music in background all time. Here is code:

package com.test.brzoracunanje;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;

public class BackgroundSoundService extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {

    return null;
}
@Override
public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();
       player = MediaPlayer.create(this, R.raw.test_cbr);
        player.setLooping(true); // Set looping
        player.setVolume(100,100);
        player.start();
}
@Override
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);
}
public void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
}

protected void onNewIntent() {
    player.pause();
}
}

But now I have problem when I click on HOME, or BACK button. It still plays music. Does anyone knows how to solve that problem?

And here is code how i call this service on class where I want to play music;

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

Answer

Jong picture Jong · Oct 28, 2011

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.