How to tell if your android app has been put in the background?

Hello,

I keep track of some statistics on my app, like run time, what buttons have been pressed etc. I would like to know is there any way to tell if my app has been put in the background (aka if the user hits the home button). I don’t wish to override it by any means I just would like to be able to send that data to my server and stop tracking it when the user does that, before android automatically closes out my app and destroys all that data.

I tried:
void OnApplicationPause(bool pauseStatus)

and that works fine in the editor, but after running some test it doesn’t get called on android after you hit the home button.

Thanks.

1 Answer

1

Ah-HA!

Using

void OnApplicationFocus(bool pauseStatus) {
    if(pauseStatus){
        //your app is in the background, yay!!!!
    }
}

It appears to be a good way to detect if your app goes into the background aka loses focus.

thanks a lot

–

Correct method, incorrect use of the attribute. In your case, pauseStatus will be true when your app is no longer in the background void OnApplicationFocus(bool pauseStatus) { if(pauseStatus){ //your app is NO LONGER in the background }else{ //your app is now in the background } }

–

This seems to be called when the app is moving to background, even though the app is still playing. For example in Android 11 -> when you start moving the app to the background it is called instantly. If you want to know when the app is completely moved to the background so that the app is also paused, you should use this function instead: private void OnApplicationPause(bool pause) { if (pause) { // App is paused } else { // App resumed } }

–