Zookey
Zookey

Reputation: 2707

Background music Android

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);

Upvotes: 10

Views: 51382

Answers (9)

mehdi dorreh
mehdi dorreh

Reputation: 303

Try to insert stopService(svc) in onDestroy() method of the activity in which service starts. It works for me.

Upvotes: 0

Anthony Cannon
Anthony Cannon

Reputation: 1273

(Kotlin) Sadly Jong's answer didn't work for me, I had a few errors including: MediaPlayer finalized without being released and a delay in stopping and starting the sound. So i'll post the way I did it just in case anyone else has the same problem. My implementation of BackgroundSound still uses AsyncTask and MediaPlayer however it is a non-nested class.

class BackgroundSound : AsyncTask<Context, Void?, Void?>() {

    override fun doInBackground(vararg params: Context): Void? {
        val player = MediaPlayer.create(params[0], R.raw.msc_background)
        player.isLooping = true
        player.start()

        while (!isCancelled) {
        }

        player.stop()
        player.release()

        return null
    }
}

You can use this class within your Activity like so:

private var backgroundSound: BackgroundSound? = null

override fun onResume() {
    super.onResume()
    backgroundSound = BackgroundSound()
    backgroundSound!!.execute(this)
}

override fun onPause() {
    backgroundSound?.cancel(true)
    super.onPause()
}

Upvotes: 0

drtom
drtom

Reputation: 1

Try to insert player.stop() in onDestroy() method. It should help.

Upvotes: 0

aks
aks

Reputation: 9491

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.

Upvotes: 2

Jong
Jong

Reputation: 9125

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.

Upvotes: 26

Janak Rajyaguru
Janak Rajyaguru

Reputation: 106

Try following to stop the background music at HOME or BACK press.

@Override
protected void onStop() {
    super.onStop();
    ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> services = activityManager
            .getRunningTasks(Integer.MAX_VALUE);
    boolean isActivityFound = false;

    if (services.get(0).topActivity.getPackageName().toString()
            .equalsIgnoreCase(getPackageName().toString())) {
        isActivityFound = true; // Activity belongs to your app is in foreground.
    }

    if (!isActivityFound) {
        if (player != null && player.isPlaying()) {
            player.release();
        }
    }
}

Upvotes: 0

user1868091
user1868091

Reputation:

write below code in your on stop method:

system. exit(0);

this will terminate your media player when you press back/home button or close application

Upvotes: 0

Srinivas
Srinivas

Reputation: 1405

yes, u should stop the service when u press the home button . In OnPause(){} override method u should stop the music service. And inside the service in OnDestroy() method u please stop the media player. So now,pressing home calls onPause and onPause() -> stops the service and OnDestroy is executed in service and in odestroy() the mediaplayer is stopped and ur problem is fixed.

Upvotes: 0

trashkalmar
trashkalmar

Reputation: 883

Sure, your service runs in background and you have to stop it manually from your activity when it goes to background.

Upvotes: 0

Related Questions