Kryonet - only one instance of a Client in the whole app

Hello. I’m sitting here for two days, can’t figure out how to do this. I’m just mentally stuck.

Let’s say that I have a main Activity when I open my app named: MainActivity

In MainActivity I have onCreate method where I set screen orientation, find ID’s etc.
The problem is here, that onCreate method is fired every time user comes back to the app, comes back with a ‘back’ button etc, so if I have:

Client client = new Client();
client.start();

It’s creating new clients (what I can see on the server (multiple connections coming from the same device: Connection1, 2, 3, 4 etc)).

So. I’ve already tried with Singletons - but this is kinda tricky and not efficiecient with network clients.
Tried with SharedPreferences, but they’re not working sometimes.
(Also tried with constructor in a main class, cause it’s fired once, but when it’s created I don’t have my declared vars yet).

Both of these solutions seem to be ‘not professional’.

My conception is that:

when user opens the app - the client is fired (but it’s not making a new connection (I handled this)). The one, static clients persists through the whole lifetime of the app (until the app is turned off). When he moves through menus etc. it’s not creating new instances. I can make operations, send packets, pass the client, everything.

If there is someone that could point me, how this should be done professionally - I would be grateful :slight_smile:

I’m sorry guys - I can declare it in the constructor…

if(null == client){
Client client = new Client();
client.start();
}

That will set a local variable client and start it, not the one you’re checking that’s null. Just drop the Client type declaration.

if(client == null){
   client = new Client();
   client.start();
}