I write simple method for udp server:
private void runUdpServer() {
String message;
byte[] lmessage = new byte[MAX_UDP_DATAGRAM_LEN];
Da
Put the code you have into a loop, and put this loop into its own thread so that it doesn't block the UI thread.
Use runOnUiThread() to update the UI from this new thread.
Example:
private MyDatagramReceiver myDatagramReceiver = null;
protected void onResume() {
myDatagramReceiver = new MyDatagramReceiver();
myDatagramReceiver.start();
}
protected void onPause() {
myDatagramReceiver.kill();
}
private class MyDatagramReceiver extends Thread {
private boolean bKeepRunning = true;
private String lastMessage = "";
public void run() {
String message;
byte[] lmessage = new byte[MAX_UDP_DATAGRAM_LEN];
DatagramPacket packet = new DatagramPacket(lmessage, lmessage.length);
try {
DatagramSocket socket = new DatagramSocket(UDP_SERVER_PORT);
while(bKeepRunning) {
socket.receive(packet);
message = new String(lmessage, 0, packet.getLength());
lastMessage = message;
runOnUiThread(updateTextMessage);
}
} catch (Throwable e) {
e.printStackTrace();
}
if (socket != null) {
socket.close();
}
}
public void kill() {
bKeepRunning = false;
}
public String getLastMessage() {
return lastMessage;
}
}
private Runnable updateTextMessage = new Runnable() {
public void run() {
if (myDatagramReceiver == null) return;
textMessage.setText(myDatagramReceiver.getLastMessage());
}
};