Search code examples
androidandroid-activityparentback

Android set back button to last activity


I have two activities which I'll call Activity A and Activity B. Activity A and Activity B both have a button that will take them to the final activity. Because I can arrive at the final activity different ways, I cannot just set a parent and navigate back to that. How can I set things so it knows which activity was used last and go back to that one?


Solution

  • In your Activity A / B when call C use:

    Intent intent = new Intent(this, ActivityC.class);
    intent.putExtra("caller", "ActivityClassName");
    startActivity(intent);
    

    In your Activity C:

    @Override
    public void onBackPressed() {
    
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        String value = extras.getString("caller");
        startActivity(this, Class.forName(value));
    } 
    }