简体   繁体   中英

onBackPressed() Best Practice/Performance

I usually override onBackPressed() like this:

@Override
public void onBackPressed() {
    super.onBackPressed();
    Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
    startActivity(intent);
    finish();
}

Only now I saw that when I click the back button with this code I see for 0.5 sec a white activity in the transition.

Testing a little bit I found that if I use this code instead the problem didn't happen:

@Override
public void onBackPressed() {
    Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
    startActivity(intent);
    finish();
    super.onBackPressed();
}

What's the difference between this two code? If I use the second one is fine? Cause any memory problem? Thanks

super.onBackPressed just calls finish. It isn't needed if you're calling finish yourself. Just remove the line.

The reason you may see a visual difference is that in one you're finishing this intent then starting a new one, vs starting a new one then finishing this one. The first may leave a blank screen briefly.

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