Johann
Johann

Reputation: 29867

Android: Terminating a thread with a socket connection

I have a thread that is used to maintain a connection to the server. If the user signs out of the service on the app (but doesn't exit the app), I need a way to terminate the thread and make sure it really is gone. As it stands, the connection to the server is done via a long poll (a.k.a, a Comet architecture). If I use "interrupt" to terminate the thread, the underlying connection to the server is still made. The thread always remains in memory. There does not appear to be any way of forcing the socket to close.

If the user signs back in right after signing out, a new connection is made to the server. However, the old connection is still active due to the socket not being released. I discovered that if I go to Android's Settings > Applications > Manage Applications and force the app to close and restart it, the connection thread is in fact terminated and I don't have a problem connecting to the server again.

Is there some way to terminate the thread after signing out so that it really is forced to be terminated? Using System.GC() doesn't help.

Upvotes: 2

Views: 441

Answers (1)

Jack
Jack

Reputation: 9242

What I do is add a boolean flag called killRequest or something that is incorporated in to the long running loop. For instance:

//long running loop in thread:
while (someMainLoopCondition && !killRequest)
{
     //do stuff;

}

Also create a method to change the flag inside the thread:

public requestTermination()
{
     killRequest = true;
}

Then you can call

myThread.requestTermination();

or create a method to cleanup for you:

private void KillNetworkThread(boolean b)
            {
                    if (nThread != null) { // If the thread is currently running, close the socket and interrupt it.
                            try {
                                    nThread.requestTermination();
                                    nis.close();
                                    nos.close();
                                    nsocket.close();
                            } catch (Exception e) {
                            }
                            Thread moribund = nThread;
                            nThread = null;
                            moribund.interrupt();
                    }

            }

This finally solved my lingering thread issue. Hope this helps!

Upvotes: 0

Related Questions