Android.os.NetworkOnMainThreadException
I. Causes of Occurrence
I wrote the network read data into the main thread
Look at the name should know, is the network request in Mainthread the exception that produces
Ii. Causes of production
Official website explanation
Class Overview
The exception is thrown when an application attempts to perform a networking operation on its main thread.
This is a thrown for applications targeting the honeycomb SDK or higher. Applications targeting earlier SDK versions is allowed to does networking on their main event loop threads, but it's heavil Y discouraged. See the document designing for responsiveness.
Also See StrictMode
.
Https://developer.android.com/intl/zh-cn/reference/android/os/NetworkOnMainThreadException.html
To explain, from the Honeycomb SDK (3.0), Google no longer allows the network request (HTTP, Socket) and other related operations directly in the main thread class, in fact, should not do so, directly in the UI thread network operation, will block the UI, The user experience is quite bad! Even if Google doesn't forbid it, we wouldn't normally do it.
So, in other words, in the Honeycomb SDK (3.0) The following version, you can continue to do so in the main thread, at more than 3.0, it is not, it is recommended
Second, the solution
Method of network operation directly in main Thread
Add the following code to the OnCreate function inside the activity that initiated the HTTP request:
1 strictmode.setthreadpolicy (new StrictMode.ThreadPolicy.Builder ()2 . Detectdiskreads (). Detectdiskwrites (). Detectnetwork ()3 . Penaltylog (). build ()); 4 Strictmode.setvmpolicy (new StrictMode.VmPolicy.Builder ()5 . Detectleakedsqlliteobjects (). Detectleakedclosableobjects ()6 . Penaltylog (). Penaltydeath () . build ());
This method is simple and useful
Detailed reference: http://blog.csdn.net/mad1989/article/details/25964495
Android.os.NetworkOnMainThreadException