Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding default back button behavior in android

I just recently learned how to clear the backstack in Android. I have two activities, one for login (LoginActivity) and one to use the application (MainActivity). It consists of a bunch of fragments. This is the code I used to start the MainActivity

Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish(); // call this to finish the current activity

Everything works fine, when I'm on the MainActivity and I press the home button, the application closes. When I open it back up, it opens the MainActivity. But when I press the back button, it's closing the application and when I open it back up, the LoginActivity is opening. How do I override the back button so it behaves the same as the home button.

like image 900
Rockstar5645 Avatar asked Dec 24 '22 06:12

Rockstar5645


1 Answers

Sounds like you want to override the back button behavior to move the app to the background instead of doing the usual back button behavior.

You can do this by overriding onBackPressed:

@Override
public void onBackPressed()
{
    moveTaskToBack(true);
}
like image 170
Allen G Avatar answered Jan 09 '23 15:01

Allen G