奇怪的問題,似乎已經提到了幾次在這裏。我有一個線程,也使用了AsyncTask,並且我正試圖根據用戶的請求使其停止運行。 因此,自然,我在while循環中使用布爾值。該線程始終將布爾值視爲true,即使在其他位置輸出false也是如此。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,但線程仍然進入while並打印出true。有什麼想法嗎?
謝謝!
你是怎麼給stopThread打電話的? – Rob
從活動中,我創建線程的一個實例,將其設置爲在該活動中運行,然後在用戶按下按鈕時調用stopThread() –
在日誌中顯示「running」的值而不是「this.running」 ... – BrainCrash