Search code examples
androidsocketsondestroy

Send last message over socket before exiting app


I have 16 clients connected to a server (2 different app projects) over sockets in Android. If a new client connects, the server keeps track of it. When a client closes the app, the server should be notified that 1 client has disconnected. The problem is that I only catch the event sometimes and sometimes the app closes too fast for the message to be sent.

What is the best practice of achieving something like that? This application is only for an internal project so the solution doesn't have to be the most beautiful piece of code as long as it works.

This is my onDestroy() method:

@Override
protected void onDestroy() {
    super.onDestroy();

    if (isConnected) {
        sendMessageToServer("ByeBye from " + MainActivity.mPreferences.getString("deviceID", "EMPTY_ID"));
    }

    if (localClient.getClientSocket() != null) {
        if (localClient.getClientSocket().isConnected()) {
            try {
                localClient.getClientSocket().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    localClient.shutdown();

    android.os.Process.killProcess(android.os.Process.myPid());
}

Solution

  • The OnDestroy() on Activities and Services isn't guaranteed to be called so you can't rely on that to send an explicit 'bye' to your server which signals the server to close down that connection.

    Since clients can and will behave unexpectedly (loss of connectivity, app crashes etc.), then the responsibility should be on the server to manage and track connection state. If you have some kind of ping or keep-alive between client and server that you send regularly then you can rely on that to also track connection state. If the server is unable to send that to the client or is not receiving it from the client for a certain amount of time, then the connection is likely dead and you can have the server consider the connection dead.