Android Socket.IO best practices for keeping connection alive Android Socket.IO best practices for keeping connection alive android android

Android Socket.IO best practices for keeping connection alive


Looking into old unanswered questions and found this one.I think the best approach is to use a bound Service that autostarts.

Using the bindService() you can bind your Activities in onResume() or onStart() and let your service close the connection and stop itself when there is no client bound on it.

You can find more information here https://developer.android.com/guide/components/bound-services


I have partial solution(won't solve your third requirement I think).I started to wrote a simple multi player game just for studing game programming.I decided to use TCP conntection(why? its another issue...), and I had to keep the connection open while the user proceeded in each Acitivty(login -> lobby -> choose opponent...),I used a Singleton patthern(double-locking check), containing the connection socket.

pseudo code

class ClientConnection{    private static ClientConnection conn = null;    Socket mSocket; // your socket      protected ClientConnection(){        mSocket = new Socket();        // mSocket.connect( bla bla bla )     }    public Socket getSocket(){        return mSocket();    }    public static ClientConnection getInstance(){        if(conn == null){            synchronized (LOCK) {                if(conn == null){                    conn = new ClientConnection();                }            }        }        return conn;            }}