0
我想在我的手機上響應多播DatagramPackets。這是保持引起ANR的部分代碼:線程在服務導致ANR
private void multicastLoop() {
String res = Build.FINGERPRINT + "\n";
final InetAddress group;
final MulticastSocket socket;
final DatagramPacket response;
try {
group = InetAddress.getByName("239.255.255.127");
socket = new MulticastSocket(port);
socket.setLoopbackMode(true);
socket.setSoTimeout(1000);
socket.joinGroup(group);
response = new DatagramPacket(res.getBytes(), res.length(), group, port);
} catch (IOException e) {
e.printStackTrace();
return;
}
Thread t = new Thread(new Runnable() {
@Override
public void run() {
while(isRunning) {
try {
byte[] data = new byte[1024];
DatagramPacket dm = new DatagramPacket(data, data.length);
socket.receive(dm);
if (Arrays.equals(dm.getData(), "someone there".getBytes())) {
socket.send(response);
}
} catch (SocketTimeoutException e) {
continue;
} catch (IOException e) {
e.printStackTrace();
}
}
try {
socket.leaveGroup(group);
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.run();
}
方法multicastLoop
是所謂的服務的onCreate
,設置isRunning = true;
爲什麼這個主題引起ANR錯誤後?在TCP-服務器多線程運行沒有問題(while (isRunning) {...}
)
OMG我真的使用'run'嗎?寫這個的時候我在想什麼? – s3lph