Search code examples
androidonbackpressed

how to onBackPressed() from another activity


can we call another activity's the function onBackPresses() ? for example, something like this: ---in second_activity----

if(i==10)
   first_activity.onBackPressed();

Solution

  • If you want to open the first activity from the press of the back button on the third one, put this in your third activity:

    @Override
    public void onBackPressed() {
        Intent intent;
        intent = new Intent(this, FirstActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        finish();
        startActivity(intent);
    }