When the BACK button is pressed on the phone, I want to prevent a specific activity from returning to its previous one.
Specifically, I have login and sign up screen
Put finish()
just after
Intent i = new Intent(Summary1.this,MainActivity.class);
startActivity(i);
finish();
@Override
public void onBackPressed() {
}
When you create onBackPressed()
just remove super.onBackPressed();
and that should work
There are two solutions for your case, activity A starts activity B, but you do not want to back to activity A in activity B.
1. Removed previous activity A from back stack.
Intent intent = new Intent(activityA.this, activityB.class);
startActivity(intent);
finish(); // Destroy activity A and not exist in Back stack
2. Disabled go back button action in activity B.
There are two ways to prevent go back event as below,
1) Recommend approach
@Override
public void onBackPressed() {
}
2)Override onKeyDown method
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_BACK) {
return false;
}
return super.onKeyDown(keyCode, event);
}
Hope that it is useful, but still depends on your situations.
Put
finish();
immediately after ActivityStart to stop the activity preventing any way of going back to it. Then add
onCreate(){
getActionBar().setDisplayHomeAsUpEnabled(false);
...
}
to the activity you are starting.
paulsm4's answer is the correct one. If in onBackPressed()
you just return, it will disable the back button. However, I think a better approach given your use case is to flip the activity logic, i.e. make your home activity the main one, check if the user is signed in there, if not, start the sign in activity. The reason is that if you override the back button in your main activity, most users will be confused when they press back and your app does nothing.
My suggestion would be to finish the activity that you don't want the users to go back to. For instance, in your sign in activity, right after you call startActivity
, call finish()
. When the users hit the back button, they will not be able to go to the sign in activity because it has been killed off the stack.