As much as I have understood from your question you need to do some logic whenever user presses back button from the app or from your device so for that :-
You need to override
activiy's lifecycle method named as onBackPressed()
. You can override that and write your required logic inside of that. It will be called whenever the user presses back button from the device itself or if you go back programatically from your activity
.
eg :-
override fun onBackPressed() {
super.onBackPressed()
// Your logic here
}
Update as mentioned in comments if you need to go back to your previous fragment from the current fragment then you need to get the callback in your current activity of that fragment. Now in that current activity you'll need to remove that fragment from your stack so you can check if there's any other fragments in the stack then you can simply pop
your current fragment or else you can execute the activity's
onBackpressed
itself.
You can refer this question on S.O and apply your own logic of handling backpressed in your fragments.