Background music Android

浪尽此生 提交于 2019-11-27 12:56:28
Jong

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.

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.

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

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.

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

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

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

(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()
}
mehdi dorreh

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!