0

我正在尝试在 Android 平板电脑上构建一个 UDP 客户端。该应用程序可以创建一个套接字就好了,但是当我尝试发送它时:

public void SendMessage( String message )
    {
        sendBuffer = message.getBytes();

        packet = new DatagramPacket( sendBuffer, sendBuffer.length, address, 4445 );
        //packet = new DatagramPacket( sendBuffer, sendBuffer.length, address, port );

        try 
        {
            socket.send( packet );
        } 
        catch (IOException ioe) 
        {
            Log.d( "NETWORK", "Failed to send UDP packet due to IOException: " + ioe.getMessage() );
            ioe.printStackTrace();
        }
        catch( Exception e )
        {
            Log.d( "NETWORK", "Failed to send UDP packet due to Exeption: " + e.getMessage() );
            e.printStackTrace();
        }
    }

Eclipse 弹出一个新窗口,显示“找不到源”,我在 LogCat 中打印了这个:

android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
at libcore.io.BlockGuardOs.sendto(BlockGuardOs.java:175)
at ...

我想知道我正在使用的端口是否被阻止或有什么东西阻止了我的 UDP 连接(因为我尝试了许多不同的端口,结果都一样)。我问这个是因为 LogCat (BlockGuardOS) 可能表明它阻止了一些输入/输出

这是实际的初始化在这里:

public ClientSocketThread( String address, int port )
    {       
        this.port = port;

        try 
        {
            this.address = InetAddress.getByName( address );
            Log.d( "NETWORK", "Address successfully resolved" );
        } 
        catch( UnknownHostException ue ) 
        {
            ue.printStackTrace();
            Log.d( "NETWORK", "Failed to resolve ip address due to UnknownException: " + ue.getMessage() );
        }

        try 
        {
            this.socket = new DatagramSocket();
            Log.d( "NETWORK", "UDP Socket successfully created" );
        } 
        catch( SocketException se ) 
        {
            Log.d( "NETWORK", "Failed to create socket due to SocketException: " + se.getMessage() );
            se.printStackTrace();
        }
    }
4

1 回答 1

6
android.os.NetworkOnMainThreadException

您不再被允许从主 (UI) 线程进行联网。你总是在文档中被警告过,但现在它被主动困住了。

该主题已在 SO 和其他来源中多次讨论。

于 2012-05-15T15:51:53.817 回答