Search code examples
androidlifecycle

Network thread which must live as long as the application is on the screen


In my application I have to connect to a server, I’m doing this in a separate thread, and I want that the connection stays active as long as any activity of my application is visible on the screen. I also want that if the user leave my application, the thread is interrupted and the connection is closed.

The main problem here is that if the user rotate the screen, the current activity is destroyed and I cannot distinguish this situation from a situation where the user is really leaving my activity. The method onRetainNonConfigurationInstance() does not work because it is called after onStop(), and I want to shut down the connection in onStop().

I also tried a bound service but the problem is exactly the same, the service is shut down when I rotate the screen.

And I do not want to handle the configuration change myself.

How can I do?


Solution

  • The onUserLeaveHint() method did the trick.