Prevent login screen on screen rotation android

前端 未结 2 655

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

相关标签:
2条回答
  • 2021-01-28 09:42

    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.

    0 讨论(0)
  • 2021-01-28 09:43

    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.

    0 讨论(0)
提交回复
热议问题