user3240604
user3240604

Reputation: 417

Android Background Music

I have a question. I see this answer: Background music Android

I don't know if it's the best way to do it or not, but the question is: What happens when you change Activity? How could you continue playing background music when you change your Activity? Do you need to create a new BackgroundSound thread?

I need to play music in background and can't find the best way to do it. I think creating a MediaPlayer in each Activity is not the best way.

Upvotes: 0

Views: 343

Answers (1)

justhecuke
justhecuke

Reputation: 1175

If you truly want your music to play when your Application has been put into the background and something else is showing on the Android Screen, then you can do the solution that the other question's asker used: start a service which plays the music.

If you want the background music to only be playing which your Application is in the foreground, then you go the route of AsyncTask. If you do this, then you only need the one AsyncTask. Its lifecycle is independent of the Activity lifecycle. Just remember that the onPreExecute and onPostExecute callbacks will be called on the UI thread that will be handling a different Activity.

Just remember that if you use AsyncTask to play background music, no other AsyncTask can be running at the same time as they all, by default, share the same background thread.

EDIT: Since you need to interact with you Background Music, then you should probably make a Service and communicate with it using Intents.

I won't write a tutorial on how to make a Service since there are already many out there. You can do a quick search and pick something up.

Inside of that Service, you want to make a LocalBroadcastManager.

myLocalManager = LocalBroadcastManager.getInstance(getApplicationContext());

Register a BroadcastReceiver and an IntentFilter to it.

Have the BroadcastReceiver check the intent that it gets for information regarding what you want you Background Music to do and then do it. The simplest way is to put an extra in in your Activity and then get it out in your Service.

Have the IntentFilter be something like "my.app.package.BackgroundMusic" to avoid name collisions.

Then, have your various activities get their own LocalBroadcastManager instance and then call sendBroadcast to tell the Service what to do. When you construct your intent, you want to use the same name as what you used to make the IntentFilter so that it will trigger the BroadcastReceiver that you wrote.

Upvotes: 1

Related Questions