Saving streams and connection status in an Android app using onSaveInstanceState?

I am developing a multi-player game application for Android. One of the participants acts as a host (the one who created the instance of the game), and each of the other participants connects to the host using bluetooth.

My question is this: this host has several threads that work for communication and contain all open connections. I read that my actions can be destroyed temporarily and later restored, and for this I have to use the onSaveInstanceState mechanism. However, I'm talking about an application that acts as a โ€œserverโ€ for the game, and has open connections and threads that serve other clients, what happens to these connections and threads if the OS decides to destroy my activity? Are they discontinued? If so, what will be the recommended template for the correct implementation, how can I save the connection in the onSaveInstanceState package? it is not serializable. The same goes for threads, do I need to recreate and destroy them when destroyed and when activity is restored ?? if I hold all this state in some kind of static class representing the state of the game? If I do this, will the OS not destroy my threads / connections?

I looked at the bluetooth chat sample that comes with the SDK and I donโ€™t handle onSaveInstanceState like that, so itโ€™s very unclear what to do.

Thanks!

+6
android android-lifecycle bluetooth
source share
1 answer

What happens to these connections and threads if the OS decides to destroy my activity?

If you created these threads in activity, you better stop these threads or leak them.

How can I save the connection in the onSaveInstanceState package?

You can not.

The same goes for flows, do I need to recreate and destroy them upon destruction and when will activity be restored?

If they were involved in the action, yes, please.

if I hold all this state in some kind of static class representing the state of the game? If I do this, will the OS not destroy my threads / connections?

Put your server logic (streams, connections, server-side logic) into the Android service. Please use startForeground() to save this service by putting Notification on the status bar along the path so that the user has an easy way to return to activity that allows them to stop your service.

+7
source share

All Articles