For Android, "NetworkOnMainThreadException" and networkonmainthread
The reasons for network collection are as follows and solutions:
I would like to add a summary:
Solution 1:
Add the following code to the protected void onCreate (Bundle savedInstanceState) function of the activity that operates the Network Class (socket connection. Add it before super. onCreate (savedInstanceState.
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads().detectDiskWrites().detectNetwork() .penaltyLog().build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects().detectLeakedClosableObjects() .penaltyLog().penaltyDeath().build());
This method is not recommended. But it is also one of the solutions.
Solution 2:
Start a new thread. This is the method shown in the figure above.
New Thread () {@ Override public void run () {// code for network operation connection mClientManage. Connect () ;}}. start ();