I'm developing a P2P chat/sharing application for android. The following code is for receiving a UDP packet but only the first message/packet is received and displayed. (There's no problem in the sending code.) Subsequent chat messages are not displayed. The while loop seems to exit after chathistory.setText(new String.... is executed. eg:chathistory.setText("test"); is not executed. Can anyone point out the error? There is no exception thrown.
public void receive() throws Exception
{
(new Thread(new Runnable() {
@Override
public void run() {
try
{
ds1=new DatagramSocket(7777);
//chathistory.setText("Holding the port...");
while(true)
{
DatagramPacket p = new DatagramPacket(buffer, buffer.length);
ds1.receive(p);
chathistory.setText(new String(p.getData(), 0, p.getLength()));
chathistory.setText("test");
}
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} })).start();
}
One, None of Androids UI calls are not threadsafe, and since your processes main thread is devoted to updating the UI, you should never manipulate UI elements in Android from any other thread but the one your activity is running in.
Two, you could be throwing an exception since logcat can't print from another thread.
Three, I'm curious if this code has ever tried to force close on you, I ask because I'm curious what android would do if the .receive blocked for a really long time, you should probably be using timeouts.