Use of onDestroy( ) in android

You can use onDestroy() to finalise the program. I have used it in the code bellow to tell the server that the client is closing its socket to the server so I can notify the user on the server end that the client has disconnected.

client:

...
protected void onDestroy(){
    super.onDestroy();
    if(connected) {
        clientMessage.println("exit");
        clientMessage.close();
        try {
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    finish();
}
...

server:

...
while (connected) {
    input = clientMessage.readLine();
    if ("exit".equals(input)){
        break;
    }
    ...
}
...

OS decides when things "go away." The onDestroy is there to let your app have a final chance to clean things up before the activity does get destroyed but it does not mean that the activity will, in fact, be GCed. Here is a good article that I recommend people to read that relates to creating an exit button. While it's not exactly what you asked about, the concepts will help you understand what's going on.


onDestroy: The final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it), or because the system is temporarily destroying this instance of the activity to save space.

Here is an example......

 public void onDestroy() {
              
   super.onDestroy();

 }