Should an App's background music have a thread of it's own? [duplicate]

不问归期 提交于 2019-12-13 18:15:39

问题


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?


回答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!



来源:https://stackoverflow.com/questions/29590703/should-an-apps-background-music-have-a-thread-of-its-own

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