Error caused by:android.os.NetworkOnMainThreadException
: Check the reason after 4.0 in the main thread inside the HTTP request will be reported this error, probably is afraid of HTTP request time too long caused the program suspended animation situation it.
There are two ways to solve the problem, namely:
First method: Direct neglect, forced use (strongly not recommended, but simple to modify)
Under Setcontentview (R.layout.activity_main) of the mainactivity file, add the following code
if (Android.os.Build.VERSION.SDK_INT > 9) {strictmode.threadpolicy policy = new StrictMode.ThreadPolicy.Builder (). Permitall (). build (); Strictmode.setthreadpolicy (policy);}
Or
See Strictmode document Strictmode.setthreadpolicy (New StrictMode.ThreadPolicy.Builder (). Detectdiskreads (). Detectdiskwrites (). Detectnetwork (). Penaltylog (). build ()); Strictmode.setvmpolicy (New StrictMode.VmPolicy.Builder (). Detectleakedsqlliteobjects (). Detectleakedclosableobjects (). Penaltylog (). Penaltydeath (). build ());
Starting with Android 2.3, a new class Strictmode can be used to capture the time-consuming disk, network access, or function calls that occur in the main thread of the application.
Can help developers improve the program, making the main thread processing UI and animations smoother on disk read and write and network operations, avoiding the main thread being blocked.
Second method: Use Thread, Runnable, Handler (recommended)
Make HTTP requests in Runnable without blocking the UI thread ~
public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); This.setcontentview ( R.layout.share_mblog_view); New Thread (runnable). Start ();} Handler Handler = new Handler () {@Override public void Handlemessage (Message msg) {super.handlemessage (msg); Bundle data = Msg.getdata (); String val = data.getstring ("value"); LOG.I ("MyLog", "request result--" + val); }}runnable Runnable = new Runnable () {@Override public void run () {/////Todo:http request.//Message msg = new Message (); Bundle data = new bundle (); Data.putstring ("value", "request result"); Msg.setdata (data); Handler.sendmessage (msg); }}
caused by:android.os.NetworkOnMainThreadException Error resolution