Search code examples
androidback-stackonbackpressed

Android onBackPressed avoid exit


When the user press the back button on his device I want to move to the previous Activity but not to go back to the Home.

For example, if the user has opened some Activities, the back stack is supposed to be:

  • Activity_A
  • Activity_B
  • Activity_C [ Currently displayed ]

When the user presses the Back button, it's supposed to get:

  • Activity_A
  • Activity_B [ Currently displayed ]

And the, if he presses the button once again:

  • Activity_A [ Currently displayed ]

Then I want to disable this button to avoid to go back to the Home screen.

Is that possible ?

So far, I'm using this method, but I've read that it won't be supported on Android L:

protected int getActivitiesStackSize()
{
    ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> taskList = am.getRunningTasks(1);
    return taskList.get(0).numActivities; 
}

@Override
public void onBackPressed()
{
    // Pop activity
    if (getActivitiesStackSize() != 1) super.onBackPressed();
}

Activity_A may be any Activity in my project.


Solution

  • you can override the back button event and then move between activities except on activity A where the back button should still exit. example

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // Check if the key event was the Back button
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
    
            //Move to previous activity
    
            return true;
        }
    
        // If it wasn't the Back key, bubble up to the default
        // system behavior
        return super.onKeyDown(keyCode, event);
    }