Problem Description:
1, the current project is 4.3, after the breakpoint debugging, know that the error occurred in
HttpURLConnection con = (httpurlconnection) url.openconnection (); // Open a connection connection Con.setrequestmethod ("GET"); Con.setconnecttimeout (the); // get the stream returned by the server InputStream is = Con.getinputstream ();//the place where the error is thrown
and report the following error:
03-14 14:27:38.428:w/system.err (30191): android.os.NetworkOnMainThreadException
03-14 14:27:38.429:w/system.err (30191): at android.os.strictmode$androidblockguardpolicy.onnetwork( strictmode.java:1134)
Solve:
After finding the information on the Internet, Android 2.3 and above are beginning to provide a new class Strictmode, which can be used to capture the time-consuming disk, network access, or function calls that occur in the main thread of the application, to help developers improve the program so that the main thread handles the UI and animations become smoother when disk reads and writes and network operations, preventing the main thread from being blocked.
Here is the exception that occurs when the main thread accesses the network. Android versions prior to 4.0 support access to the network in the main thread, but after 4.0, this part of the program is optimized, that is, the code to access the network can not be written in the main
Thread.
The relevant information on the Internet, the main thread to add the following code to solve:
Strictmode.setthreadpolicy (new StrictMode.ThreadPolicy.Builder (). Detectdiskreads (). Detectdiskwrites (). Detectnetwork ()
//
. Penaltylog () // print Logcat, and of course you can navigate to Dropbox and save the corresponding log by file build ()); Strictmode.setvmpolicy ( new StrictMode.VmPolicy.Builder (). Detectleakedsqlliteobjects () // Explore SQLite database operations . Penaltylog () //
Report android.os.NetworkOnMainThreadException Error