1, Exception: Android.os.NetworkOnMainThreadException
After android2.3, you must use another thread, such as the handler mechanism, or an asynchronous task to get network data in the main thread
If your access to the network must be performed in the main thread, add the following in OnCreate ():
Public voidonCreate (Bundle savedinstancestate) {//See Strictmode documentationStrictmode.setthreadpolicy (NewStrictMode.ThreadPolicy.Builder (). Detectdiskreads (). Detectdiskwrites () . Detectnetwork ()//or. Detectall () for all detectable problems. Penaltylog (). build ()); Strictmode.setvmpolicy (NewStrictMode.VmPolicy.Builder (). Detectleakedsqlliteobjects (). Detectleakedclosableobject S (). Penaltylog (). Penaltydeath (). build ()); Super. OnCreate (savedinstancestate); Setcontentview (R.layout.main); InitDialog ();}
This allows the network operation to be performed in the main thread in the high version, or the thread can be restarted to perform network operations:
Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); This. Setcontentview (R.layout.share_mblog_view); NewThread (runnable). Start ();} Handler Handler=NewHandler () {@Override Public voidhandlemessage (Message msg) {Super. Handlemessage (msg); Bundle Data=Msg.getdata (); String Val= Data.getstring ("Value"); LOG.I ("MyLog", "request result--" +val); }} Runnable Runnable=NewRunnable () {@Override Public voidrun () {// //todo:http request. //Message msg =NewMessage (); Bundle Data=NewBundle (); Data.putstring ("Value", "Request Result"); Msg.setdata (data); Handler.sendmessage (msg); }}
Extensions: Handler mainly accepts the data sent by the child thread, and uses this data to update the UI with the main thread, reference http://www.pin5i.com/showtopic-android-handler.html
Multithreading reference : http://www.cnblogs.com/ccdc/p/3836966.html