简体   繁体   English

Android:使用套接字连接终止线程

[英]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 (aka, a Comet architecture). 就目前而言,到服务器的连接是通过长时间的轮询(又称Comet体系结构)完成的。 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. 我发现,如果转到Android的“设置”>“应用程序”>“管理应用程序”,并强制关闭应用程序并重新启动它,则连接线程实际上已终止,并且再次连接服务器没有问题。

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. 使用System.GC()没有帮助。

What I do is add a boolean flag called killRequest or something that is incorporated in to the long running loop. 我要做的是添加一个称为killRequest的布尔标志,或者将其添加到长时间运行的循环中。 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! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM