In Android development, If you are using Android4.0 later, you will find that the runtime will make an error if the HTTP request is written in the main thread (that is, activity), since Android is 4.0 in order to prevent the application of ANR (aplication not Response) exception
In the Android Api>9 (Honeycomb and later) version, the UI thread/mainline thread is not allowed to operate on the Internet, and if there is a network operation, a Networkonmainthreadexception exception is thrown.
There are two ways to solve this problem:
1. Ignore These enforcement policies: you can add such a piece of code to the activity's OnCreate () method as follows:
if (Build.VERSION.SDK_INT >= 11) {
Strictmode.setthreadpolicy (New StrictMode.ThreadPolicy.Builder (). Detectdiskreads (). Detectdiskwrites (). Detectnetwork (). Penaltylog (). build ());
Strictmode.setvmpolicy (New StrictMode.VmPolicy.Builder (). Detectleakedsqlliteobjects (). Detectleakedclosableobjects (). Penaltylog (). Penaltydeath (). build ());
}
You can then perform network operations in the main thread.
2. Re-opening a thread: we should do it in general.
There is a good way to keep your app responsive, which is to get the main UI thread to do as little as possible, and if a lengthy process is done in the UI thread, it can cause the UI to be zombie, so for a task that might take too long, another thread should be processed. The typical application scenario is to do network-related operations, because there may be unexpected delays in the network transmission process. Typically, a user can tolerate a small wait on feedback, but a zombie interface is another matter.
Then we'd better call the network and start a sub-thread to make your network request.
Of course, if your application executes a small amount of network request data, you can use the first
Reference:
http://www.android-study.net/listxx.aspx?id=659
Http://www.tuicool.com/articles/ba6fEv
About the Android main thread exception Networkonmainthread cannot access the network