Skip to content Skip to sidebar Skip to footer

How To Implement Onretainnonconfigurationinstance

i made a media player in android it's working great but when i change the screen orientation, the activity is being restarted i know that this question was already asked on stacko

Solution 1:

I believe that onRetainNonConfigurationInstance() is deprecated. It will tell you to use Fragments instead. Here is a link to the Fragment documentation. Basically, you will put your UI and data into a custom Fragment, then use the FragmentManager to store an instance of your Fragment. Then, when the activity restarts, you can fetch your Fragment and reposition as needed.

Solution 2:

Never mind that it's deprectated, it works fine. Simplest would be:

publicObjectonRetainNonConfigurationInstance() {
   returnthis;
}

Then in YourActivity's onCreate()

publicvoidonCreate(Bundle savedState)
{
   YourActivityprevActivity= (YourActivity)getLastNonConfigurationInstance();
   if(prevActivity!= null) { 
       // So the orientation did change// Restore some field for examplethis.myValue = prevActivity.myValue;
   }
}

Solution 3:

In my media player, in order not to re-create MediaPlayer completely, I did the following:

1) In AndroidManifest.xml added

<activityandroid:name=".MainActivity"android:configChanges="orientation|screenSize">

2) Inside the MainActivity added

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    setSize(mVideoWidth, mVideoHeight);
}

I hope this helps someone.

Post a Comment for "How To Implement Onretainnonconfigurationinstance"