Search code examples
androidandroid-asynctasknionetworkonmainthread

android.os.NetworkOnMainThreadException and non blocking sockets


I using Java nio sockets in non blocking mode, but when i call write i still get 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.
}

I will expect this to work as the socket will not block and just return 0 in case the call need to block. But i still receive the 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

Solution

  • android.os.NetworkOnMainThreadException :

    The exception that is thrown when an application attempts to perform a networking operation on its main thread.

    use AsyncTask for making network related task from Ui Thread

    or you are using API LEVEL 9 then just set StrictMode for Current Activity in onCreate() method before making network request :

       StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
       .detectNetwork() // or .detectAll() for all detectable problems
       .penaltyDialog()  //show a dialog
       //.permitNetwork() //permit Network access 
       .build());