Losing 'MediaPlayer' (& other Variables) when Device is Rotated

后端 未结 4 1502
独厮守ぢ
独厮守ぢ 2021-01-07 13:06

I\'m creating a music player for Android and it\'s mostly working. The problem is that when I turn the device horizontally I lose all the variables from the Activity (which

4条回答
  •  粉色の甜心
    2021-01-07 13:30

    Both of the methods below would allow you to keep your mediaplayer object through the rotation, but neither use bundles.

    • You could persist your media player by using onRetainNonConfigurationInstance() to save the variable and getLastNonConfigurationInstance() to retrieve it after the rotation, but this method isn't necessarily the best as it is not always called

      -See this SO post for more info https://stackoverflow.com/a/3916068/655822

    • Or you could persist your media player by extending your application class and storing it in there

      below info copied from the linked SO answer for the purpose of making this answer quicker to read

      You can pass data around in a Global Singleton if it is going to be used a lot.

      public class YourApplication extends Application 
      {     
           public SomeDataClass data = new SomeDataClass();
      }
      

      Then call it in any activity by:

      YourApplication appState = ((YourApplication)this.getApplication());
      appState.data.UseAGetterOrSetterHere(); // Do whatever you need to with the data here.
      

      -See this SO post for more info on that https://stackoverflow.com/a/4208947/655822

提交回复
热议问题