服务中的线程导致 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();
    }

设置isRunning = true;为什么此线程会导致 ANR 错误后,在服务的onCreate中调用方法multicastLoop?TCP-服务器-线程运行没有问题 ( while (isRunning) {...}

您需要调用t.start();而不是t.run();

t.run()只会在导致 ANR 的当前线程(UI)上执行Runnable

最新更新