简体   繁体   中英

Empty activity when resuming after onBackPressed in Android

I have got a strange problem with my Android app.

How my app works: When I start my app it launches the MainActivity. If the user is not logged in it then launches LoginActivity and after that finish is called in the MainActivity.

Now when the LoginActivity is launched and I press the back button the app closes. When I open the app again it has to launch the LoginActivity again, but sometimes this is not working (like 1 of the 8 times). When it doesn't work the app just shows me an empty activity.

When the app doesn't launch correctly (2nd printscreen) the buttons/text inputs do work, but it looks like they are just hidden or something. So when I press at the position of the ' Sign Up ' text it does take me to the RegisterActivity.

Does somebody know what causes this strange behaviour?

This is when the app is launched correctly: 良好的启动

But this is what happens sometimes: 发射不良

MainActivity onCreate:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    initializeDataSources();

    if(usersDataSource.getCurrentUser() == null)
    {
        Intent LoginActivity = new Intent(getApplicationContext(), LoginActivity.class);
        LoginActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(LoginActivity);
        finish();
        return;
    }

    if(localServiceBinder == null)
        localServiceBinder = new LocalServiceBinder();

    bindLocalService();

    setContentView(R.layout.activity_main);
}

LoginActivity onCreate:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if(localServiceBinder == null)
        localServiceBinder = new LocalServiceBinder();

    bindLocalService();

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_login);

    mUsernameView = (EditText) findViewById(R.id.username);
    mPasswordView = (EditText) findViewById(R.id.password);
    mSignInButton = (Button) findViewById(R.id.sign_in_button);
    mSignUpButton = (TextView) findViewById(R.id.sign_up_button);
}

Move your data work and login activity call to onStart/onResume. You get "empty" activity when onDestroy/onCreate dont calls when activity hide and shows again. When this: if(usersDataSource.getCurrentUser() == null) is true, this:

if(localServiceBinder == null)
            localServiceBinder = new LocalServiceBinder();

bindLocalService();

setContentView(R.layout.activity_main);

became a dead code for case: onPause -> onStop -> onStart -> onResume in lifecycle of your activity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM