You need to call t.start();
instead of t.run();
t.run()
will just execute the Runnable
on the current thread (the UI) which causes the ANR.
質問
I'm trying to respond to multicast DatagramPackets on my phone. This is the part of the code that keeps causing the 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();
}
The method multicastLoop
is called in the onCreate
of the Service, after setting isRunning = true;
Why does this Thread cause an ANR error? The TCP-Server-Thread is running without problems (while (isRunning) {...}
)
解決
You need to call t.start();
instead of t.run();
t.run()
will just execute the Runnable
on the current thread (the UI) which causes the ANR.