您无法在主线程中接收或执行网络流量。
您必须创建一个单独的可运行线程来执行此操作:
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();
然后在一个单独的类代码中,可能会干扰主 UI 的可运行任务。
final Runnable alertMsg = new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), alertMessage, Toast.LENGTH_LONG).show();
}
};