2

I am not sure how to get this information on my apps: how to know when an activity has been restarted because of a configuration change? (any configuration change).

In my code I need to execute a method if the activity restarted "normally" but not because of a configuration change.

Lucifer
  • 29,392
  • 25
  • 90
  • 143
Yoann Hercouet
  • 17,894
  • 5
  • 58
  • 85

3 Answers3

3

When the onConfigurationChanged() method to detect the Orientation changes.

Class level variable

private boolean isOrientationChanged = false; 

Assign true value when orientation gets changed

@Override
public void onConfigurationChanged(Configuration newConfig) 
{
    super.onConfigurationChanged(newConfig);
    isOrientationChanged = true;
}

Check value in onRestart() method and reset it

@Override 
public void onRestart() 
{
    if ( isOrientationChanged ) 
    {
          isOrientationChanged = false;         // reset the  variable for future action.
          // Your code
    }
}
Lucifer
  • 29,392
  • 25
  • 90
  • 143
  • Yes I thought about that, but it implies that I change my manifest to add all the possible configurations in the tag `android:configChanges`. If it is the only way I will do it but I thought there would be maybe something more simple. – Yoann Hercouet Apr 14 '14 at 05:43
  • @YoannHercouet, hmm lets see what other users provide the solution. – Lucifer Apr 14 '14 at 05:44
  • I upvoted your answer because it is a solution, but I leave it open in case someone provides one more straightforward – Yoann Hercouet Apr 14 '14 at 06:02
  • @YoannHercouet, ok, even I too want to see what is better/best solution for this requirement. May be I will need it in my next application. – Lucifer Apr 14 '14 at 06:04
3

When an Activity is being restarted due to configuration changes, it is guaranteed that onDestroy() method will be called. In onDestroy() method, you can use isChangingConfigurations(), to check whether Activity is being destroyed inorder to be recreated due to configuration changes. Since Activity state cannot be saved as onSaveInstanceState() will be called before onStop() method, you think of using SharedPreference to save the state and latter retrieve it in onCreate() method.

By handling this in onDestroy() method, we ensure that we handle a case of background Activity which was previously started say in Portrait mode, now trying to be displayed in Landscape mode.

Manish Mulimani
  • 17,535
  • 2
  • 41
  • 60
1

You can use OnConfigurationChange method for checking the current config.

public void onConfigurationChanged(Configuration newConfig) {

if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
{

}
else if(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
{

}
    super.onConfigurationChanged(newConfig);
}