服务中的线程导致ANR

时间:2014-01-16 20:32:38

标签: android multithreading android-service multicast

我正在尝试在手机上响应多播DatagramPackets。这是导致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-Server-Thread正在运行而没有问题(while (isRunning) {...}

1 个答案:

答案 0 :(得分:1)

您需要致电t.start();而不是t.run();

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