2011-09-09 4 views
1

여기에 몇 번 언급 된 것처럼 보이는 이상한 문제. 스레드가 있고 AsyncTask도 사용했으며 사용자 요청에 따라 AsyncTask가 실행을 중지하려고합니다. 당연히 while 루프에서 부울을 사용합니다. 스레드는 항상 다른 곳에서 false를 인쇄 할 때조차도 boolean을 true로 봅니다.Android - while 루프를 사용하여 스레드 중지

아래 코드는 도움이됩니다.

/** 
* 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); 
} 

stopThread()를 호출하면 false가되지만 스레드는 여전히 잠시 동안 진입하여 사실을 인쇄합니다. 이견있는 사람?

감사합니다.

+0

어떻게 stopThread를 호출합니까? – Rob

+0

작업에서 스레드의 인스턴스를 만들고, 해당 활동에서 실행되도록 설정 한 다음 사용자가 단추를 누를 때 stopThread()를 호출합니다. –

+0

로그에 "this.running"대신 "running"값이 표시됩니다. ... – BrainCrash

답변

1

가능한 원인 : 둘 이상의 스레드를 양산하고 단지 중 하나를 폐쇄 한

1).

2) 스레드가 실행되기 전에 stopThread으로 전화하십시오.

3) 스레드가 UI 스레드에서 많은 logTextView.append(logput) 호출을 대기열에 넣었으므로 이 이후에 계속 실행 중임을 나타냅니다.

+0

아마도 세 번째 가능성을 다시 확인하기 위해 while 루프 다음에 로그 출력을 추가하십시오. – Zharf

+0

감사 합니다만, 세 번째 가능성에 대한 로그 출력은 여전히 ​​보여 주지만 텍스트 뷰를 업데이트하는 것으로 보이지 않지만 또 다른 문제입니다. 하나의 스레드 만 활동에 의해 생성되고 하나 이상의 메시지를받은 후에 만 ​​스레드가 중지됩니다. 그것은 이상한 것이다. –

관련 문제