简体   繁体   中英

Back Button press initiate onDestroy then onCreate again of same activity

I have 2 main Activities, login and list, which uses firebase auth. after few times of login and logout, if I press the back button (happens on both activities) the same activity reloads (although I use finish() when intenting between them).

i tried to override onBackButtonPressed, but nothing worked. I printed messages in onCreate and onDestroy to make sure they are called.

Login Activity (only relevant pieces)

public class LoginActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        Log.wtf("TESTING", "CREATED: " + getClass().getSimpleName() + " -- TASK ID: " + getTaskId());

        setAllOutlets();
        mAuth = FirebaseAuth.getInstance();



    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.wtf("TESTING", "DESTROYED: " + getClass().getSimpleName() + " -- TASK ID: " + getTaskId());
    }


    private void goToListActivity(){

        Intent listActivityIntent = new Intent(LoginActivity.this, com.technion.android.mylists.ListActivity.class);
        startActivity(listActivityIntent);
        finish();

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }
}

List Activity is about the same, ill add it if someone will say it's needed, because its pretty big... i use auth state listener and made sure Im calling finish when user clicks log out button

for both activities I would like to press the back button and minimize the app, regardless of what activity the user is in.

Try this,

@Override
public void onBackPressed() {
     super.onBackPressed();
     finish();
     moveTaskToBack(true);
}

https://developer.android.com/reference/android/app/Activity.html#moveTaskToBack(boolean)

As I remember, you don't need to call finish() if you are overloading OnBackPressed()

In this case it's reasonable

@Override
public void onBackPressed() {
    switch (behaviorOptionsGroup.getCheckedRadioButtonId()) {
        case R.id.finish:
            finish();
            return;
        case R.id.moveTaskToBack:
            moveTaskToBack(false);
            return;
        default:
            super.onBackPressed();
    }
}

In your case, i guess, you call finish() twice. Once in super.onBackPressed(); and second time explicitly then you call it after.

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