I need to act differently in onStart()
method depending on how onCreate()
was called in result
of orientation change
or not. Is that possible to check it?
Actually what I need is to do something
when activity starts except a case when user changes orientation.
I need to clearly distinguish cases when user just switched to another application and returned back OR he changed device's orientation.
First onPause(), onStop() and onDestroy() will be called simultaneously and after some time when the activity restarts the onCreate(), onStart() and onReume() methods will be called simultaneously. So when you change the orientation of a screen the Activity will be restarted.
The Android documentation says the method onCreate is called only when is starting or when is destroyed. Why is this happening? Thanks!! Regars.
@OnCreate is only for initial creation, and thus should only be called once. If you have any processing you wish to complete multiple times you should put it elsewhere, perhaps in the @OnResume method.
OnCreate will only be called one time for each lifetime of the Activity. However, there are a number of situations that can cause your activity to be killed and brought back to life. Thus, onCreate will be called again.
Following Nahtan's idea I wrote this:
in onCreate():
if ( (oldConfigInt & ActivityInfo.CONFIG_ORIENTATION)==ActivityInfo.CONFIG_ORIENTATION ) {
// ... was rotated
} else {
// ... was not rotated
}
in onDestroy():
super.onDestroy();
oldConfigInt = getChangingConfigurations();
public class MyActivity extends Activity {
boolean fromOrientation=false;
SharedPreferences myPrefLogin;
Editor prefsEditor;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefsEditor = myPrefLogin.edit();
myPrefLogin = this.getSharedPreferences("myPrefs", Context.MODE_WORLD_READABLE);
fromOrientation = myPrefLogin.getString("fromOrient", false);
if(fromOrientation) {
// do as per need--- logic of orientation changed.
} else {
// do as per need--- logic of default onCreate().
}
}
@Override
public Object onRetainNonConfigurationInstance() {
prefsEditor.putString("fromOrient", true);
prefsEditor.commit();
return null;
}
@Override
protected void onDestroy() {
if(fromOrientation) {
prefsEditor.putString("fromOrient", false);
prefsEditor.commit();
}
super.onDestroy();
}
}
flag fromOrientation(tells the state either configuration had been change or not)
above we had done like by defalut we are considering that onCreate()
is not called from by changing orientation. If orientation changed(onRetainNonConfigurationInstance()
) then we set the flag value in preference which let us know whether onCreate()
is called from on orientation or not.
And finally onDestroy()
we again reset the orientation flag.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With