Background music Android
Asked Answered
B

9

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);
Biotope answered 28/10, 2011 at 11:47 Comment(2)
I don't see where the problem is... Didn't you want to play music in background ALL the time?Weiner
I want to play it all time while application is running, but when I press Home button music still plays.Biotope
B
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.

Bareback answered 28/10, 2011 at 11:57 Comment(14)
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?Biotope
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.Bareback
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?Biotope
It says mBackgroundSound cannot be resolved when I put onResume and onPause method under activity class.Biotope
Make sure you declared mBackgroundSound as a field in your activity class.Bareback
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()Biotope
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.Bareback
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.Biotope
The method onResume() is undefined for the type AsyncTask<Void,Void,Void>Biotope
If you started the same activity from its onResume it will cause an infinite loop. Fixed the code. And you really should read developer.android.com/guide/topics/fundamentals/activities.htmlBareback
I fixed it, and run it, but still same shit, when I press HOME button music still plays. I will go crazy about this.Biotope
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 developer.android.com/reference/android/media/… so you can understand what are you/I do wrong.Bareback
@Bareback 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.Ross
I want to run music throughout the app. Shall I start in application class?Velocity
A
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.

Alasteir answered 29/3, 2016 at 17:30 Comment(0)
P
0

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

Partible answered 28/10, 2011 at 11:51 Comment(0)
P
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.

Patentee answered 20/1, 2012 at 5:34 Comment(0)
M
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

Milligram answered 18/1, 2014 at 15:3 Comment(0)
E
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();
        }
    }
}
Engedi answered 31/7, 2014 at 17:35 Comment(0)
J
0

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

Jolty answered 13/1, 2017 at 23:14 Comment(0)
L
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()
}
Larkins answered 24/4, 2018 at 9:27 Comment(0)
S
0

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

Strobel answered 3/8, 2019 at 16:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.