1

I'm trying to build an app where a piece of Music is played whenever the onCreate() is called, and I want for this music to be played throughout the whole app ie across Activities. what I've done so far is to create a Thread,within the OnCreate(), and I called it backgroundMusic, inside of it I created A MediaPlayer Object from a music piece in my Raw Folder. given that the music itself only runs for a minute or so and the average time spent on the app is more, I made a while Loop that as long as the app is running checks if the music is playing, if not then call start();

backgroundMusic = new Thread(new Runnable() {
    @Override
    public void run() {
        while ( appIsRunning ){

            if( ! music.isPlaying () ){
                music.start();
            }
        }
    }
});backgroundMusic.start();

the code runs just fine, however I did notice some Lag especially later when some other Threads and Images gets loaded.what I want to ask, is this an appropriate way to play background Music? is there a better more efficient way of doing that? also, how do I make the music stop as the app closes?

RaedTabani
  • 13
  • 3

1 Answers1

1

is this an appropriate way to play background Music?

No, you need to declare music on a service. A service :

  • Will be independent of activity LifeCycle hence music will keep playing when Activity is closed

  • can be paused when needed like incoming call

Here is something to get you started. Happy coding!

Community
  • 1
  • 1
Karan
  • 2,120
  • 15
  • 27
  • thanks Kay, this is what I was looking for. I want to ask you if the Service run in the UI thread and if so would I need a Thread inside of it? – RaedTabani Apr 12 '15 at 15:19
  • glad that it helped! Music on UI thread is fine, since a new Service will also spawn on the UI thread. However, you can also start a Thread inside a service but its not needed for Music Player. Feel free to accept the answer:) – Karan Apr 12 '15 at 15:22
  • absolutely :) however can I get your feedback on ToasteR's answer? he suggested using an Asynctask – RaedTabani Apr 12 '15 at 15:29
  • AsycTasks are for short lived operations like network calls, so data can be displayed to user onPostExecute(). A user can hear music for hours at a stretch, so service is the way to go. it is highly impractical unless they are short bursts of noice like pre-listening ringtones when selecting one.. – Karan Apr 12 '15 at 15:33
  • Sorry to resurrect this, but @Kay can you please explain why : Music on UI thread is fine, since a new Service will also spawn on the UI thread ? If my UI thread will be doing other operations from the activity, will it still perform well without any slowness ?? – duskandawn Aug 24 '16 at 16:50