我在非阻塞模式下使用 Java nio 套接字,但是当我调用 write 时,我仍然得到 NetworkOnMainThreadException。
java.nio.channels.SocketChannel fd = Network.createTcpSocket();
java.nio.channels.SocketChannel.open();
java.net.Socket socket = fd.socket();
socket.setTcpNoDelay(true);
socket.setKeepAlive(true);
fd.configureBlocking(false);
//.. conect the socket
int ret = fd.write(data);
if(ret == 0)
{
// It will block.
}
我希望这可以工作,因为套接字不会阻塞,并且在调用需要阻塞的情况下只返回 0。但我仍然收到 NetworkOnMainThreadException
12-07 18:50:25.704: W/dalvikvm(14931): threadid=1: thread exiting with uncaught exception (group=0x40c501f8)
12-07 18:50:25.834: E/AndroidRuntime(14931): FATAL EXCEPTION: main
12-07 18:50:25.834: E/AndroidRuntime(14931): android.os.NetworkOnMainThreadException
12-07 18:50:25.834: E/AndroidRuntime(14931): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
12-07 18:50:25.834: E/AndroidRuntime(14931): at libcore.io.BlockGuardOs.sendto(BlockGuardOs.java:168)
12-07 18:50:25.834: E/AndroidRuntime(14931): at libcore.io.IoBridge.sendto(IoBridge.java:477)
12-07 18:50:25.834: E/AndroidRuntime(14931): at java.nio.SocketChannelImpl.writeImpl(SocketChannelImpl.java:369)
12-07 18:50:25.834: E/AndroidRuntime(14931): at java.nio.SocketChannelImpl.write(SocketChannelImpl.java:327