开发者

Android - Stopping a thread using a while loop

Weird problem that seems to have been mentioned a few times on here. I have a thread, have used AsyncTask also, and I am trying to make it stop running, on the users request. So, naturally, I use a boolean in the while loop. The thread always sees that boolean as true, even when it prints false elsewhere.

Code is below and any help is appreciated!

/**
 * Opens new socket and listens on the specified port until a user stops the thread, the logview is updated with messages
 */
public void run() {
    byte[] receiveData = new byte[1024];
    byte[] sendData = new byte[1024];
    Log.e("Text2Server", "Starting Server");
    this.running = true;
    while(this.running) {
        Log.i("Text2Server", "Server should be running: " +  running);
        try {
            serverSocket = new DatagramSocket(port);
        } catch (SocketException e1) {
            e1.printStackTrace();
        }
        try {   
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            serverSocket.receive(receivePacket);
            final String fromIP = new String(receivePacket.getAddress().toString());
            final int fromPort = receivePacket.getPort();
            final String received = new String(receivePacket.getData());
            Date now = new Date();
            final String logput = DateFormat.getDateTimeInstance().format(now) + " - Message from: " + fromIP + " through Port: " + fromPort + " with Message: " + received;
            Log.i("Text2Server", logput);
            //All UI Operations are done in this thread
            uiHandler.post(new Runnable(){
                @Override
                public void run() {
                    logTextView.append(logput);
                }                   
            });
        }开发者_高级运维 catch (Exception e) {
            e.printStackTrace();
        }
    }
    serverSocket.close();
}

public void stopThread() {
    this.running = false;
    Log.i("Text2Server", "Stopping Server, value is now: " + running);
}

Calling stopThread() makes it false, but the thread still goes into the while and prints out true. Any thoughts?

Thanks!


Possible reasons:

1) You have spawned more than one thread and have closed only one of them.

2) You call stopThread before the thread starts running.

3) The thread has queued up many logTextView.append(logput) calls on the UI thread and therefore appears to be still running afterwards.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜