I have an Android Activity that extends AppCompatActivity
and I am getting very confused because when I test it on my phone ( a Sony Xperia on Android 7.1.1, API 25 ) the onPause
method is not called when the Home button is pressed.
In fact it appears as though no Activity Lifecycle events are triggered by the app being put in the background. I have the following in my Activity:
@Override
public void onPause()
{
super.onPause();
Log.i(TAG, "Pause the Activity.");
}
@Override
public void onStop() {
super.onStop();
Log.i(TAG, "Stop the Activity");
forceClose();
}
@Override
protected void onUserLeaveHint(){
super.onUserLeaveHint();
Log.i(TAG, "User leaving the Activity");
forceClose();
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (!hasFocus)
{
Log.i(TAG, "Window focus changed- Activity no longer has focus.");
}
}
When I hit the "Home" button, none of these are called. In fact there doesn't seem to be anything happening in my code, my app just vanishes from view. If I start a different app, all of the Activity closing lifecycle calls - including onPause
- suddenly happen at that point.
This is a problem for me because the activity is fairly battery intensive and I don't want to waste the user's battery if they have put it in the background. Also it doesn't seem to recover well from being backgrounded, so it seems easier to cancel it.
There are various questions about this on SO ( this might be closest ) but none of them seem to cover this scenario - the onPause
documentation suggests that it is called when an app is sent to the background, but in other places I have seen it suggested that it is only called when another app is launched, so possibly that explains what I am seeing.
How can I find when my app has been sent to the background?