This question already has an answer here:
- Android background music service 7 answers
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?