If you are a beginner, it is recommended to first understand the Android lifecycle:
The relevant documentation is here: The android lifecycle
According to your needs, I think you need onPause
.
If you want to be called when the user kills the app, then you need to handle it in onDestroy
in MainActivity
.