I have made an App in android in which i have a TCP Client but now i want to send a message to the server only when the app is going to be closed, i've trying to add the openConnection
(opening connection with TCP Client) and sendMessage
(Sending message to the TCP server) action in onDestroy method but that didn't worked.
The TCP Client i've used is in this guide, actually i need to send this message for communicate the server that the communication with the device is closed and send message "Device is Offline" and just then close the app.
How can i do something before app is closed?
1.8k Views Asked by John K AtThere are 3 best solutions below

Following method call on diff action
Minimize the Application using home button --> this calls
onPause() onStop()
Remove the app from Task Manager ->
then onDestroy() is called for that MainActivity (launcher).
So Make an parent Activity suppose named BaseActivity and override its onPause(), onDestroy() and onStop() method and call your implementation from here and then extend this Activity from your another Activities

You should not rely on the onDestroy method. As per the official android documentation it is not called always.
Try to put the same code in the onStop() method of your activity.
Additionally you can have a parent activity which is extended by all other activities.
You can then override the onPause() and onStop() method in your particular child activities and handle the specific scenarios.
Method 1: You can use ActivityLifecycleCallbacks to achieve this. There's an example with some logs below.
Method 2: There's another method using Service to detect if application is terminated. See link