You can't receive or do network traffic in the main thread.
You have to create a separate runnable thread to do that:
new Thread(new Runnable() {
public void run() {
try {
if (clientsocket == null) {
clientsocket = new DatagramSocket(null);
clientsocket.bind(new InetSocketAddress("0.0.0.0", 1337));
clientsocket.setBroadcast(true);
}
byte[] receivedata = new byte[1024];
while (true) {
DatagramPacket recv_packet = new DatagramPacket(
receivedata, receivedata.length);
clientsocket.receive(recv_packet);
alertMessage = new String(recv_packet.getData());
InetAddress ipaddress = recv_packet.getAddress();
int port = recv_packet.getPort();
String msg = "RECEIVED UDP MSG FROM " + ipaddress.toString() + ":" + Integer.toString(port) + " :" + alertMessage; Log.d("UDP", msg);
myHandler.post(alertMsg);
}
} catch (Exception e) {
Log.e("UDP", "S: Error", e);
}
}
}).start();
then in a separate class code the runnable task that could interfere with the main UI.
final Runnable alertMsg = new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), alertMessage, Toast.LENGTH_LONG).show();
}
};