问题
I have an application in which a login screen shows up whenever an activity goes to onPause state. Generally, when screen orientation changes, the activity goes to onPause state, so I somehow prevented login screen when device is rotated. See the code below,
protected void onPause() {
super.onPause();
WindowManager mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mDisplay = mWindowManager.getDefaultDisplay();
mOrientation = mDisplay.getRotation();
if(mOrientation == 1 || mOrientation == 2 || mOrientation == 3 || mOrientation == 0)
{
inApp = true;
}
if (!inApp) {
SavedState.setState(this, "HomeActivity");
Intent intent = new Intent(HomeActivity.this, LoginActivity.class);
startActivity(intent);
}
}
But the problem is when i press home button and comes back to the application, the login screen is not showing up instead it is directly resuming to the activity, because mDisplay.getRotation()
reads the screen current orientation and if
condition always becomes true.
To put it simple and clear, I need the login screen to be shown when the user presses Home button or switches to other application but not when the screen is rotated.
Any kind of suggestion or example is much appreciated. Thanks !
回答1:
Here's something that should work -- you might have to flesh it out a bit...
class MyActivity... {
private boolean loggedIn = false;
@Override
protected void onSaveInstanceState( Bundle data ) {
super.onSaveInstanceState( data );
data.putBoolean( "loggedIn", loggedIn );
}
@Override
protected void onUserLeaveHint() {
isLoggedIn = false; // user pressed home
}
@Override
protected void onCreate( Bundle data ) {
isLoggedIn = data.getBoolean( "loggedIn", false );
....
}
@Override
protected void onResume() {
if( !isLoggedIn ) {
/// Log in...
}
}
This pattern uses/restores the state of the activity using the preferred method, and as a bonus, logs out the user if the Home button is pressed (or the user activity decides to move to a different app). Note that phone-calls should not log the user out here -- which in most cases is the desired behavior.
Make sure you remove the android:configChanges
garbage that someone else recommended.
回答2:
By default, Android will actually destroy and restart your activity on rotation. This causes onPause()
, onStop()
, onDestroy()
, onCreate()
, onStart()
, onResume()
to be called. The best way to avoid problems like this is to tell Android not to do that. In the manifest add android:configChange="orientation"
to your Activity. It will prevent the destruction, and call a function on rotation instead. It will still correctly redraw your screen in almost all cases.
来源:https://stackoverflow.com/questions/14863594/prevent-login-screen-on-screen-rotation-android