My application have some activities which in the first one I connect a socket to communicate with a server on the others activities. This socket runs in a worker thread.
My question is: where can I close this socket when the application is finishing? Using the BACK button for instance...
I thought close the socket in onDestroy()
of the last activity but this activity can be destroyed by the system at runtime and close the socket even if the application is not finishing. I don't want this.
My run()
method of the thread handling the socket connection is 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 anyone give me some hint?
The finally
block is never executed because the run loop never completes. At some point Android just kills the process, which kills the VM and everything just goes away.
If you have an application that just contains activities and you are doing network I/O in a separate thread then there is no way for you to know when to shut the thread down because the "application" is never "finished". You need to define how the application "finishes".
A better way is to put this into a Service, because if Android wants to kill the process it will first call onDestroy() in the Service which will give you a chance to shutdown your thread properly.
running
or the thread gets killed. Network handling required by multiple Activities sounds like a good place to move that into a Service - zapl 2012-04-04 22:14