0

I got a exception when I run that code on my android server device but I don't understand why, can you please help me.

WifiP2pDevice peer = wifiP2pDeviceList.getDeviceList().iterator().next();
String host = peer.deviceAddress;
ServerSocket serverSocket = new ServerSocket(2009);
Socket client = serverSocket.accept(); // I got the exception here

Exception : FATAL EXCEPTION: main android.os.NetworkOnMainThreadException

arezkibe
  • 13
  • 1
  • 6

2 Answers2

0

Android recognizes a network call as potentially non-responsive, so it prevents you from doing this on the UI thread. You need to make the call in AsyncTask or in a background process. See this:

http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html

And additional (popular) explanation of the error:

How to fix android.os.NetworkOnMainThreadException?

Community
  • 1
  • 1
Jim
  • 10,172
  • 1
  • 27
  • 36
0

That's because networking related stuff is not allowed in UI thread but there's a workaround, just add these lines in your onCreate, below the setContentView(to avoid any mistakes :) )

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

But it would be a good practice if you do it on a Non-UI thread.

Sarthak Mittal
  • 5,794
  • 2
  • 24
  • 44