I am working on an application that maintains a connection for several purposes, such as publishing an receiving location updates. As per the android way of doing things and advice from other answers I have not overridden the default android behavior of destroying and recreating the application on screen rotation, and things do work nicely in that regard.
I keep hold of the connection with the onRetainNonConfigurationInstance method. The problem is that I would like to close the connection when the user presses Home, the application is minimized or for some other reason loses focus but NOT when the screen is rotated – I can therefore not do this in onPause, onStop, or OnDestroy without some checks, since they are called one after the other on configuration changes. As it is right now I use isFinishing() to check whether the application is being closed – but the case where the user presses Home does not entail isFinishing() == true (which makes sense).
One solution I have thought of is checking whether the application has focus in the thread handling the connection updates and simply close it if some time has passed without focus – but I feel like there must be some better way of doing this?
Thanks in advance for your time.
(Edited to clear things up with regards to the activity lifecycle and onRetainNonConfigurationInstance, after reading the answers posted)
I finally found the hook method onUserLeaveHint() in Activity, which does what I want at least for the cases I have seen so far. That is, the connection is kept open during restarts due to configuration changes but are closed when the user presses home or back. Thus, the solution I ended up with is something like the code below. Everything irrelevant to the question has been snipped and names have been simplified.