Playing BG Music Across Activities in Android

后端 未结 6 881
南方客
南方客 2020-11-27 06:27

Hello! First time to ask a question here at stackoverflow. Exciting! Haha.

We\'re developing an Android game and we play some background music for our intro

6条回答
  •  春和景丽
    2020-11-27 07:10

    First i used the method where to keep a "keepMusicPlaying" flag provided by Chad. I think its more elegant to just use the onStart and onStop methods of your activitys.

    Create an own class "SoundManager" and call some onStart and onStop classes in it from all your activitys onStart and onStop (or use a base activity class). Keep track of the onStart and onStop with a startCounter(startCounter++ in onstart and startCounter-- in onstop). Because the start of a new activity is called before the onStop of the old activity you always know if the onStart is called for the first Time (startCounter == 1) or started from another of your activitys (startCounter == 2). Same with the onStope(startCounter == 0 means the App was closed, startCounter == 1 means its just the stop from an old activity but there is a new).

    This way you encapsulate everything into your SoundManager instead of having to call some keepMusicPlaying method/flag on every activity start inside your app.

        public void OnStart()
        {
            startCounter++;
            if (startCounter == 1)
            {
                //start music here
            }
    
        public void OnStop()
        {
            startCounter--;
            if (startCounter == 0)
            {
                // stop music here
            }
        }
    

提交回复
热议问题