4

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.

Rockstar5645
  • 4,376
  • 8
  • 37
  • 62

3 Answers3

9

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);
}
Allen G
  • 1,160
  • 6
  • 8
1

You can use activity's method.

from activity,

onBackPress()

from fragment,

getActivity().onBackPress()
ErShani
  • 392
  • 2
  • 9
0

You can start Luncher Application in your MainActivity's onBackPressed(),it seems you press the home button.

According to :Going to home screen programmatically

 @Override
public void onBackPressed() {
    Intent startMain = new Intent(Intent.ACTION_MAIN);
    startMain.addCategory(Intent.CATEGORY_HOME);
    startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(startMain);
}
Community
  • 1
  • 1
banking
  • 480
  • 2
  • 9