You should understand the activity lifecycle first
when the activity comes int the foreground it'll enter onPause() and it'll enter onResume if the user returns to the activity, an example to use onPause is like this
@Override
public void onPause() {
super.onPause(); // Always call the superclass method first
// DO YOUR STUFF HERE
}
}
for furthere reference about onPause you can see it here -> onPause Tutorial