10

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);
Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
Zookey
  • 2,637
  • 13
  • 46
  • 80
  • I don't see where the problem is... Didn't you want to play music in background ALL the time? – m0skit0 Oct 28 '11 at 11:51
  • I want to play it all time while application is running, but when I press Home button music still plays. – Zookey Oct 28 '11 at 16:28

9 Answers9

26

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.

Nick Cardoso
  • 20,807
  • 14
  • 73
  • 124
Jong
  • 9,045
  • 3
  • 34
  • 66
  • Just one question. Do I need to make new class BackgroundSound ? or put this under BackgroundSoundService class, or put this inside my main activity class? – Zookey Oct 28 '11 at 17:17
  • 1
    In your activity class, where you want to play the sounds. It has to be a inner class. Remember to change "YourActivity" (In the code) to your activity name. – Jong Oct 28 '11 at 17:20
  • 4
    I have test it. It play sounds when I start app, but problem is when I press HOME button it still plays music while app is closed? – Zookey Oct 28 '11 at 17:34
  • It says mBackgroundSound cannot be resolved when I put onResume and onPause method under activity class. – Zookey Oct 28 '11 at 17:46
  • Make sure you declared mBackgroundSound as a field in your activity class. – Jong Oct 28 '11 at 17:49
  • Now i get this error 10-28 17:52:17.733: ERROR/AndroidRuntime(225): java.lang.RuntimeException: Unable to resume activity {com.test.brzoracunanje/com.test.brzoracunanje.PocetnaActivity}: android.app.SuperNotCalledException: Activity {com.test.brzoracunanje/com.test.brzoracunanje.PocetnaActivity} did not call through to super.onResume() – Zookey Oct 28 '11 at 17:53
  • True, I forgot to call Activity.onPause and onResume. But come on... this is fundamental, by the time you are playing music you should have read the Activity documentation... Fixed it. – Jong Oct 28 '11 at 17:56
  • I have tried to call activity with startActivity under onPause and onResunme, but it doesnt work. Yeah i know thats fundemental but I am newbie. – Zookey Oct 28 '11 at 18:00
  • The method onResume() is undefined for the type AsyncTask – Zookey Oct 28 '11 at 18:02
  • If you started the same activity from its onResume it will cause an infinite loop. Fixed the code. And you really should read http://developer.android.com/guide/topics/fundamentals/activities.html – Jong Oct 28 '11 at 18:03
  • I fixed it, and run it, but still same shit, when I press HOME button music still plays. I will go crazy about this. – Zookey Oct 28 '11 at 18:08
  • http://pastebin.com/jzw2j9WR Here is the fixed one. I think it should work, but I have never used MediaPlayer so I can't tell. I suggest you to read the MediaPlayer documentation http://developer.android.com/reference/android/media/MediaPlayer.html#start() so you can understand what are you/I do wrong. – Jong Oct 29 '11 at 16:04
  • @Jong be carefull onCancelled might not be called right away with cancel. You probably have to create a method In the created class to do the player.stop() and player.release() instead putting them in the onCancelled method. And then, u call that method before the cancel. – jmacedo Aug 09 '12 at 01:44
  • I want to run music throughout the app. Shall I start in application class? – Prashanth Debbadwar Jul 22 '15 at 11:27
2

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.

aks
  • 8,796
  • 11
  • 50
  • 78
0

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

0

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();
        }
    }
}
0

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

drtom
  • 1
  • 1
0

(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()
}
Anthony Cannon
  • 1,245
  • 9
  • 20
0

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

Adam Michalik
  • 9,678
  • 13
  • 71
  • 102
mehdi dorreh
  • 173
  • 1
  • 12
0

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

trashkalmar
  • 883
  • 5
  • 11
0

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.

Srinivas
  • 1,405
  • 2
  • 13
  • 15