Most answers are calling finish()
when you want to close the activity. This works fine for most cases but in some situations this doesn't work. For example, in Android 13, when you press back on the last activity in the stack and return to the home screen, onDestroy()
is not called immediately and app remains in memory. If you open up the app again right then, it starts from onStart()
.
So, in some situations its better to let the system handle the closing of the app, or in the other words, let super.onBackPressed()
happen.
To replace this
override fun onBackPressed() {
if(showPopUpBeforeClosing){
showDialog()
} else {
super.onBackPressed()
}
}
do this -
onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
if (showPopUpBeforeClosing) {
showDialog()
} else {
//Removing this callback
remove()
onBackPressedDispatcher.onBackPressed()
}
}
})
If you add a callback to the onBackPressedDispatcher
, and call onBackPressedDispatcher.onBackPressed()
, it always calls handleOnBackPressed()
. There is no method like onSuperBackPressed() or something to let the system know to handle the backPress on its own once you're done. If you don't add the callback, then the system does its own thing, but if you've added it, then calling onBackPress will invoke handleOnBackPressed()
. So what we do is, once you're done handling the back-press, you callback.remove()
the callback removes itself and now when you do onBackPressedDispatcher.onBackPressed()
, it will not invoke handleOnBackPressed()
and handle the back-press as the system would do, which is equivalent to super.onBackPressed()
.