I’m developing an Android 3.1 Tablet application that runs a service with this thread:
public class UDPServerThread extends Thread
{
[ ... ]
public void run()
{
while (!end)
{
try
{
byte[] buf = new byte[MESSAGE_SIZE];
// Wait an incoming message.
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
// TODO: Notify Service with packet received
Message msg = new Message();
msg.obj = packet;
mServiceHandler.sendMessage(msg);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
public void stopServer()
{
Log.v("UDPServerThread", "stopServer");
if (socket != null)
socket.close();
end = true;
}
}
When I call stopServer() method from service I get the following error:
java.net.SocketException: Interrupted system call
Which is the right way to stop this thread while it is on socket.receive(packet);?
The only real problem with this exception is that you cannot easily distinguish it from an actual I/O error. I’d suggest switching to using a SocketChannel rather than a Socket — then you can interrupt your server thread and it will throw a ClosedByInterruptException instead, which you can catch and handle specifically.