0

我正在为 android 开发 P2P 聊天/共享应用程序。以下代码用于接收 UDP 数据包,但仅接收并显示第一个消息/数据包。(发送代码没有问题。) 不显示后续聊天消息。chathistory.setText(new String.... 执行后while循环似乎退出了。 eg:chathistory.setText("test"); 没有执行。谁能指出错误?没有抛出异常。

public void receive() throws Exception
        {
        (new Thread(new Runnable() {

        @Override
        public void run() {
            try 
            {
                ds1=new DatagramSocket(7777);
                //chathistory.setText("Holding the port...");

                while(true)
                {

                    DatagramPacket p = new DatagramPacket(buffer, buffer.length);
                    ds1.receive(p);
                    chathistory.setText(new String(p.getData(), 0, p.getLength()));
                    chathistory.setText("test");

                }
            }
                    catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
        }   

        } })).start();
    }
4

1 回答 1

0

一,Android 的 UI 调用都不是线程安全的,并且由于您的进程主线程专门用于更新 UI,因此您不应从任何其他线程操作 Android 中的 UI 元素,但您的活动正在运行的线程除外。

第二,您可能会抛出异常,因为 logcat 无法从另一个线程打印。

三,我很好奇这段代码是否曾试图强制关闭你,我问是因为我很好奇如果 .receive 阻塞很长时间,android 会做什么,你可能应该使用超时。

于 2011-10-15T21:53:36.250 回答