Closing a socket at application termination

My application has some actions that in the first connect a socket to communicate with the server in other actions. This socket is running in a worker thread.

My question is: where can I close this socket when the application ends? For example, using the BACK button ...

I thought to close the socket in onDestroy() last action, but this action can be destroyed by the system at runtime and close the socket even if the application does not end. I do not want it.

My run() method of the thread handling the socket connection looks like:

 public void run() { if (this.bliveclient.isConnected()){ try { //... while (running) { //waiting for input data and do something... } } catch (IOException ex) { //handle exception } finally{ try { mySocket.close(); } catch (IOException ex) { //handle exception } } } 

But the finally block is never called.

Can someone tell me?

+6
source share
1 answer

The finally block is never executed, because the cycle loop never ends. At some point, Android just kills the process, which kills the VM, and everything just quits.

If you have an application that simply contains actions, and you perform network I / O in a separate thread, then you cannot find out when to close the stream because the “application” is never completed. You need to determine how the application “ends” "

It’s best to put this in the Service, because if Android wants to kill the process, it will first call onDestroy () on the Service, which will give you the opportunity to close your thread correctly.

+4
source

Source: https://habr.com/ru/post/912439/


All Articles