Question

My MainActivity starts another thread called UdpListener. In onResume, the thread will be started (this works), in onPause it should stop, but socket.close() causes an error message in LogCat "the system call was canceled". The UdpListener itself works fine in JUnit tests so this must be some kind of Android problem.

These are the corresponding methods of my thread:

private void setThreadRunning(boolean running) throws MyOwnException {
    this.running = running;

    if (running) {
        try {
            serverSocket = new DatagramSocket(9800);
        } 
        catch (SocketException e) {
            exceptionThrown = true;
            this.running = false;
            Log.e(TAG, e.getMessage());

            if (serverSocket != null && !serverSocket.isClosed())  {
                serverSocket.close();
            }

            throw new MyOwnException(e);
        }
    } 
    else {
        if (serverSocket != null && !serverSocket.isClosed())  {
            serverSocket.close();
        }
    }
}

public void stopThread() throws MyOwnException {
    setThreadRunning(false);
}

MainActivity.onPause():

@Override
public void onPause()  {
    super.onPause();

    try {
        udpListener.stopThread();
    } 
    catch (MyOwnException e) {
        //TODO AlertDialog
    }
}

serverSocket.close() of else branch will be executed and causes the LogCat entry, but why?

UPDATE
Maybe Dalvik recognize this as error because close() throws SocketExceptions on every thread currently block in "receive", but I'm not sure if this Exception is related to this problem.

http://docs.oracle.com/javase/1.4.2/docs/api/java/net/DatagramSocket.html#close()

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top