我已经考虑这个问题好几个小时了,但我离解决方案还差得很远! 当我出于某种原因从服务器获取消息时,我的线程只是停止循环,而当我不这样做时,它会完美地工作。
这有效并每秒打打印新:
public class ChatRoom extends Activity implements OnClickListener, Runnable {
private Thread t = new Thread(this);
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chatroom);
Button send = (Button) findViewById(R.id.send);
send.setOnClickListener(this);
Intent receiver = getIntent();
String host = receiver.getStringExtra("Host");
int port = receiver.getIntExtra("Port", 4456);
try
{
socket = new Socket(host, port);
this.receive = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
this.send = new PrintWriter(this.socket.getOutputStream(), true);
}
catch(IOException ioe) { System.out.println(ioe); }
t.start();
}
public void run()
{
String message = "";
while(true)
{
try
{
// message = receive.readLine(); BufferedReader
t.sleep(1000);
}
//catch(IOException ioe) { System.out.println(ioe); }
catch (NullPointerException npe) { System.out.println(npe); }
catch (InterruptedException e) { System.out.println(e); }
System.out.println("Refreshing...");
}
}
当我使用我的评论代码时,它确实有效,我从服务器收到一条消息,但它只循环一次!这是为什么?
Output:
Server Message
Refreshing...
我没有收到任何异常或错误,但我之前遇到过一些类似代码的错误,说我无法在其他线程上更改 UI。所以我一直在看一些 runOnUiThread 但它并没有让它变得更好,而且我不知道为什么它应该 :(
最佳答案
方法BufferedReader.readLine()
阻塞直到接收到换行符。如果您的接收器流中没有换行符,它将永远阻塞。
关于android - 线程只循环一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8028084/