Search code examples
javaandroidback-button

Exit application on back button using getOnBackPressedDispatcher


To override the back button's action in API below 33, one could use

@Override
public void OnBackPressed(){
  finish();
}

Now that this has been deprecated, I am trying to get the getOnBackPressedDispatcher to work.

From my first activity, I start a second one using the call back for a button:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void openSecondActivity(View view) {
        Intent intent = new Intent(this, SecondActivity.class);
        startActivity(intent);
    }
}

Now, in the second activity, I want the back button to exit the app.

public class SecondActivity extends AppCompatActivity  {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed(){
                finish();
            }
        });
    }
}

This, however, doesn't work. Pressing the back button takes me back to the first activity.

What am I doing wrong?


Solution

  • You should close your first activity when moving to the second one, by calling finish.

    public class MainActivity extends AppCompatActivity {
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    
    public void openSecondActivity(View view) {
        Intent intent = new Intent(this, SecondActivity.class);
        startActivity(intent);
        finish();       /// <----- HERE
     }
    }
    

    Also, I would recommend reading up on launch modes.