Loss of MediaPlayer (and other variables) when the device is rotated

I am creating a music player for Android, and it works mostly. The problem is that when I rotate the device horizontally, I lose all the variables from the Activity (which makes sense because it is destroyed and recreated).

I tried using packages to store player state using onSaveInstanceState and onRestoreInstanceState, but I still can’t access media players. Is there a way to pass objects like MediaPlayer into packages? Should I use a database instead?

thank

0
source share
4 answers

"" , .

android_packages_apps_Music, CM github. MediaPlaybackService , checkout MediaPlaybackService.java

+4

, , SharedPreference . :

public class Data {
     private SharedPreferences preferences; 
     private int test; 

     public Data (Context context)
     {          
        preferences = context.getSharedPreferences("Data", 0);
        test = preferences.getInt("test", 0);
     }

     public int getTest()
     {       
             return test;
     }

     public void setTest(int input)
     {       
        this.test = input;
        SharedPreferences.Editor editor = preferences.edit();
        editor.putInt("Test", input);
        editor.commit();
     }    
}

onCreate():

mydata = ();

set/get mydata / .

: , MediaPlayer, (int, string, boolean...).

+1

, .

  • , onRetainNonConfigurationInstance(), getLastNonConfigurationInstance(), , ,

    - fooobar.com/questions/105711/...

  • ,

    , SO-,

    Global Singleton, .

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

    :

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

    - SO fooobar.com/questions/57163/...

+1

:

AndroidManifest.xml :

android:configChanges="orientation|screenSize"

.

0

All Articles