Exception: Android.os.NetworkOnMainThreadException
Android 4.1 project: Share the Times with Sina Weibo:
Android.os.NetworkOnMainThreadException
Online search after know because of the version of the problem, after 4.0 in the main thread inside the HTTP request will be reported this error, perhaps is afraid of HTTP request time too long cause the program suspended animation situation it. Then on-line friends have also given the corresponding solution, which is called on the policy has countermeasures:
One: Add the following code to the OnCreate function inside the activity that initiated the HTTP request:
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 ());
If you are doing a project that is not Android 4.0, you cannot see the Strictmode class. I also use the Internet to give the Com_weibo_android.jar. But when the jar is downloaded, it's 2.3, it's going to be converted to Android 4.0, and then the two lines of code are added to the OnCreate () function that shares the corresponding shareactivity. This will not be reported in this error.
Two: Use thread, Runnable, handler these three classes:
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);} }
Android4.0 issues with HTTP requests over version