Android's android.os.NetworkOnMainThreadException anomaly

Source: Internet
Author: User
Tags dotnet wsdl

When using the Android test to access the Web server's WebService, Access WebService in the main thread of mainactivity, with the following code:

Package Com.example.myandroidpro;import Java.io.file;import Org.ksoap2.soapenvelope;import Org.ksoap2.serialization.soapobject;import Org.ksoap2.serialization.soapserializationenvelope;import Org.ksoap2.transport.httptransportse;import Android.annotation.suppresslint;import Android.app.Activity;import Android.os.bundle;import Android.os.environment;import Android.os.strictmode;import Android.view.View;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.toast;public Class Mainactivity extends Activity {    private static String NAMESPACE = "http://service.cxf.test/";  & nbsp  //WebService address     private static String URL = "http://192.168.1.119:8080/CxfWebService/services /helloservice/";    private String method_name = null;    private button activity_main_ btn1;     @SuppressLint ("Newapi") @Override     protected void OnCreate (Bundle Savedinstancestate) {        super.oncreate (savedinstancestate);         Setcontentview (R.layout.activity_main);        Strictmode.threadpolicy policy=new StrictMode.ThreadPolicy.Builder (). Permitall (). Build ();         Strictmode.setthreadpolicy (Policy);                 File rootdirectory = Environment.getrootdirectory ();//Get the phone root directory          File storagedirectory = Environment.getexternalstoragedirectory ();//get SD card root directory          for (File file:rootDirectory.listFiles ()) {             system.err.println (file.isdirectory () + "," +file.getname ());        }                 Findview ();                 Activity_main_btn1.setonclicklistener ( New Onclicklistener () {                         @Override             public void OnClick (View arg0) {                //send WebService request                     sayhi ("Zxn");                 }        });            }    private void Findview () {         activity_main_btn1 = (Button) Findviewbyid (R.ID.ACTIVITY_MAIN_BTN1);    }     private string Sayhi (string name) {        string Result = null;        //(1) Specify the namespace of the WebService and the method name of the call          Method_name = "Sayhi";        soapobject soapobj = new Soapobject (NAMESPACE, Method_name) ;        /**         * (2) sets the parameter value of the calling method, which can be omitted if there are no parameters. Note that the parameter must correspond to the variable name inside the @webparam of the service declaration          */         Soapobj.addproperty ("name", name);        //(3) Generates SOAP request information that calls the WebService method. This information is described by the Soapserializationenvelope object Description         soapserializationenvelope envelope = new Soapserializationenvelope (                 SOAPENVELOPE.VER11);        //envelope.bodyout = rpc;       & Nbsp;envelope.dotnet = false;        envelope.setoutputsoapobject (soapobj);nbsp;       //(4) Create Httptransportsse objects. You can specify the WebService WSDL document url        httptransportse HT = new by constructing the Androidhttptransport class Httptransportse (URL);        try {            //(5) Use the Call method to invoke the WebService method             ht.call (null, envelope);             //(6) Use the GetResponse method to obtain the return result of the WebService method             if (envelope.getresponse ()! = null) {                system.out.println (Envelope.getresponse ());                 result = string.valueof (Envelope.getresponse ());                toast.maketext (mainactivity.this, result, Toast.length_short)                         .show ();            }        } catch (Exception e) {            e.printstacktrace ();        }         return result;    }}

Due to the network access in the main thread, the Android version is 4.3, causing the following exception:

<span style= "Background-color:rgb (255, 204, 255); >05-15 02:00:05.769:w/system.err (2269): android.os.networkonmainthreadexception05-15 02:00:05.799:w/system.err (2269): at Android.os.strictmode$androidblockguardpolicy.onnetwork (strictmode.java:1133) </span>05-15 02:00:05.799:w/system.err (2269): at Libcore.io.BlockGuardOs.connect (blockguardos.java:84) 05-15 02:00:05.810:w/ System.err (2269): at Libcore.io.IoBridge.connectErrno (iobridge.java:144) 05-15 02:00:05.810:w/system.err (2269): at Libcore.io.IoBridge.connect (iobridge.java:112) 05-15 02:00:05.869:D/DALVIKVM (2269): Gc_for_alloc freed 345K, 14% free 2674k/3076k, paused 48ms, total 52ms05-15 02:00:05.869:w/system.err (2269): at Java.net.PlainSocketImpl.connect ( plainsocketimpl.java:192) 05-15 02:00:05.880:w/system.err (2269): at Java.net.PlainSocketImpl.connect ( plainsocketimpl.java:459) 05-15 02:00:05.880:w/system.err (2269): at Java.net.Socket.connect (socket.java:842) 05-15 02:00:05.889:w/system.err (2269): at Libcore.net.httP.httpconnection.<init> (httpconnection.java:76) 05-15 02:00:05.889:w/system.err (2269): at Libcore.net.http.httpconnection.<init> (httpconnection.java:50) 05-15 02:00:05.899:w/system.err (2269): at Libcore.net.http.httpconnection$address.connect (httpconnection.java:340) 05-15 02:00:05.899:w/system.err (2269): At Libcore.net.http.HttpConnectionPool.get (httpconnectionpool.java:87) 05-15 02:00:05.899:w/system.err (2269): at Libcore.net.http.HttpConnection.connect (httpconnection.java:128) 05-15 02:00:05.899:w/system.err (2269): at Libcore.net.http.HttpEngine.openSocketConnection (httpengine.java:316) 05-15 02:00:05.899:w/system.err (2269): at Libcore.net.http.HttpEngine.connect (httpengine.java:311) 05-15 02:00:05.909:w/system.err (2269): at Libcore.net.http.HttpEngine.sendSocketRequest (httpengine.java:290) 05-15 02:00:05.909:w/system.err (2269): at Libcore.net.http.HttpEngine.sendRequest (httpengine.java:240) 05-15 02:00:05.909:w/system.err (2269): at Libcore.net.http.HttpURLConnectionImpl. Connect (httpurlconnectionimpl.java:81) 05-15 02:00:05.909:w/system.err (2269): at Libcore.net.http.HttpURLConnectionImpl.getOutputStream (httpurlconnectionimpl.java:197) 05-15 02:00:05.919:w/ System.err (2269): at Org.ksoap2.transport.ServiceConnectionSE.openOutputStream (serviceconnectionse.java:126) 05-15 02:00:05.919:w/system.err (2269): at Org.ksoap2.transport.HttpTransportSE.call (httptransportse.java:185) 05-15 02:00:05.929:w/system.err (2269): at Org.ksoap2.transport.HttpTransportSE.call (httptransportse.java:118) 05-15 02:00:05.929:w/system.err (2269): at Org.ksoap2.transport.HttpTransportSE.call (httptransportse.java:113) 05-15 02:00:05.969:w/system.err (2269): at Com.example.myandroidpro.MainActivity.sayHi (mainactivity.java:77) 05-15 02:00:05.969:w/system.err (2269): at Com.example.myandroidpro.mainactivity.access$0 (MainActivity.java:58) 05-15 02:00:05.969:w/system.err (2269): at Com.example.myandroidpro.mainactivity$1.onclick (MainActivity.java:47) 05-15 02:00:05.969:w/system.err (2269): AT Android.view.View.performClick (view.java:4240) 05-15 02:00:05.979:w/system.err (2269): at android.view.view$ Performclick.run (view.java:17721) 05-15 02:00:05.979:w/system.err (2269): at Android.os.Handler.handleCallback ( handler.java:730) 05-15 02:00:06.012:w/system.err (2269): at Android.os.Handler.dispatchMessage (handler.java:92) 05-15 02:00:06.012:w/system.err (2269): at Android.os.Looper.loop (looper.java:137) 05-15 02:00:06.019:w/system.err ( 2269): At Android.app.ActivityThread.main (activitythread.java:5103) 05-15 02:00:06.019:w/system.err (2269): at Java.lang.reflect.Method.invokeNative (Native Method) 05-15 02:00:06.019:w/system.err (2269): at Java.lang.reflect.Method.invoke (method.java:525) 05-15 02:00:06.034:w/system.err (2269): at Com.android.internal.os.zygoteinit$methodandargscaller.run (zygoteinit.java:737) 05-15 02:00:06.034:w/system.err ( 2269): At Com.android.internal.os.ZygoteInit.main (zygoteinit.java:553) 05-15 02:00:06.039:w/system.err (2269): at Dalvik.system.NativeStart.main (NatIve Method) 

Reason:

Android.os.NetworkOnMainThreadException is to say do not access the network in the main thread, this is the android3.0 version of the Force program cannot access the network in the main thread, to put the access network in a separate thread.

Solve:

In the development, in order to prevent the access network to block the main thread, it is generally necessary to put the access network in a separate thread or asynchronous thread asynctask.

Add the following configuration to the Androidmanifest.xml file manifest node First:

<uses-permission android:name= "Android.permission.INTERNET"/>

1, if you want to ignore these mandatory policy issues, you can add in the OnCreate () method

Strictmode.threadpolicy policy=new StrictMode.ThreadPolicy.Builder (). Permitall (). build (); Strictmode.setthreadpolicy (Policy);
and add @suppresslint ("Newapi") to the method, Retry, OK.


2. Place network access in a separate thread:

Package Com.example.myandroidpro;import Java.io.file;import Org.ksoap2.soapenvelope;import Org.ksoap2.serialization.soapobject;import Org.ksoap2.serialization.soapserializationenvelope;import Org.ksoap2.transport.httptransportse;import Android.annotation.suppresslint;import Android.app.Activity;import Android.os.bundle;import Android.os.environment;import Android.os.handler;import Android.os.Looper;import Android.os.message;import Android.os.strictmode;import Android.view.view;import Android.view.View.OnClickListener Import Android.widget.button;import Android.widget.toast;public class Mainactivity extends Activity {private static String NAMESPACE = "http://service.cxf.test/";//WebService address private static String URL = "http://192.168.1.119:8080/ cxfwebservice/services/helloservice/";p rivate String method_name = null;private button Activity_main_btn1;private int Android_access_cxf_webservices = 001; Private Handler Handler = new Handler () {@Overridepublic void Handlemessage (Message msg) {String result = (string) msg.getdata (). Get ("result");    String obj = (string) msg.obj;//activity_main_btn1.settext ("Request result:" +result);}};        protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                Setcontentview (R.layout.activity_main); File RootDirectory = Environment.getrootdirectory ();//Get phone root directory File storagedirectory = Environment.getexternalstorag EDirectory ();//get SD card root for (File file:rootDirectory.listFiles ()) {System.err.println (file.isdirectory () + ",        "+file.getname ());                } findview (); Activity_main_btn1.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (view view) {Thread            Accesswebservicethread = new Thread (new Webservicehandler ()); Accesswebservicethread.start ();}}); } class Webservicehandler implements runnable{@Overridepublic void Run () {looper.prepare (); String result = Sayhi ("Zxn"); Message message = new Message (); Bundle bundle = New Bundle (); bundle.putstring ("result", result); message.what = android_access_cxf_webservices;//Set message Flag Message.obj = " ZXN "; message.        SetData (bundle);//message content Handler.sendmessage (messages);//Send Message Looper.loop ();} private void Findview () {activity_main_btn1 = (Button) Findviewbyid (R.ID.ACTIVITY_MAIN_BTN1);} private string Sayhi (string name) {string result = null;//(1) Specifies the namespace of WebService and the method name called Method_name = "Sayhi"; Soapobject soapobj = new Soapobject (NAMESPACE, method_name);/** * (2) sets the parameter value of the calling method, which can be omitted if there are no arguments. Note that the parameter must correspond to the variable name inside the @webparam of the service Declaration */soapobj.addproperty ("name", name), or (3) generate the SOAP request information that calls the WebService method. This information is described by the Soapserializationenvelope object Soapserializationenvelope envelope = new Soapserializationenvelope ( SOAPENVELOPE.VER11);//envelope.bodyout = Rpc;envelope.dotnet = False;envelope.setoutputsoapobject (SOAPOBJ);// (4) Create a Httptransportsse object. The Androidhttptransport class can be constructed by specifying the URLHTTPTRANSPORTSE HT = new Httptransportse (URL) of the WebService WSDL document; try {//(5) Use the call method to invoke the WebService method Ht.call (NULL, EnveloPE);//(6) Use the GetResponse method to obtain the return result of the WebService method if (envelope.getresponse () = null) {SYSTEM.OUT.PRINTLN ( Envelope.getresponse ()); result = String.valueof (Envelope.getresponse ()); Toast.maketext (mainactivity.this, result, Toast.length_short). Show ();}} catch (Exception e) {e.printstacktrace ();} return result;}}

The corresponding layout of the mainactivity is as follows:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:paddi ngbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_horizontal_margin" Android: paddingright= "@dimen/activity_horizontal_margin" android:paddingtop= "@dimen/activity_vertical_margin" tools: Context= ".        Mainactivity "> <linearlayout android:layout_width=" fill_parent "android:layout_height=" Fill_parent " android:orientation= "vertical" > <textview android:id= "@+id/activity_main_tv1" Android  : layout_width= "match_parent" android:layout_height= "wrap_content" android:text= "@string/hello_world"            /> <button android:id= "@+id/activity_main_btn1" android:layout_width= "Match_parent"       android:layout_height= "Wrap_content"     android:text= "@string/test_for_cxf_webservice"/> </LinearLayout></RelativeLayout> 

3, put network access into the asynchronous task Asynctask, the code is as follows:

Package Com.example.myandroidpro;import Java.io.file;import Org.ksoap2.soapenvelope;import Org.ksoap2.serialization.soapobject;import Org.ksoap2.serialization.soapserializationenvelope;import Org.ksoap2.transport.httptransportse;import Android.app.activity;import Android.os.asynctask;import Android.os.bundle;import Android.os.environment;import Android.view.view;import Android.view.View.OnClickListener Import Android.widget.button;public class Mainactivity extends Activity {private static String NAMESPACE = "Http://servi ce.cxf.test/";//WebService address private static String URL =" http://192.168.1.119:8080/CxfWebService/services/    helloservice/";p rivate String method_name = null;private button activity_main_btn1;        protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                Setcontentview (R.layout.activity_main); File RootDirectory = Environment.getrootdirectory ();//Get phone root directory File storagedirectory = Environment.getexternalstoragEDirectory ();//get SD card root for (File file:rootDirectory.listFiles ()) {System.err.println (file.isdirectory () + ",        "+file.getname ());                } findview (); Activity_main_btn1.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (view view) {Accesswsaction ();} private void Accesswsaction () {new asynctask<string, void, object> () {//after Doinbackground execution is complete, onpostexecute The method is called by the UI thread, which is passed to the UI thread by this method, and displayed to the user on the interface. protected void OnPostExecute (Object result) {Super.onpostexecute ( result); Activity_main_btn1.settext ("Request result is:" +result);//can update ui}//the method runs in a background thread, so the Ui,ui thread cannot be updated in that thread for the main thread protected Object doinbackground (String ... params) {string result = Sayhi ("Zxn");//activity_main_btn1.settext ("Request result:" +result); return result;}}.    Execute ();}}); }private void Findview () {activity_main_btn1 = (Button) Findviewbyid (R.ID.ACTIVITY_MAIN_BTN1);} private string Sayhi (string name) {string result = null;//(1) Specifies the namespace of WebService and the method name called Method_name = "SayhI "; Soapobject soapobj = new Soapobject (NAMESPACE, method_name);/** * (2) sets the parameter value of the calling method, which can be omitted if there are no arguments. Note that the parameter must correspond to the variable name inside the @webparam of the service Declaration */soapobj.addproperty ("name", name), or (3) generate the SOAP request information that calls the WebService method. This information is described by the Soapserializationenvelope object Soapserializationenvelope envelope = new Soapserializationenvelope ( SOAPENVELOPE.VER11);//envelope.bodyout = Rpc;envelope.dotnet = False;envelope.setoutputsoapobject (SOAPOBJ);// (4) Create a Httptransportsse object. The Androidhttptransport class can be constructed by specifying the URLHTTPTRANSPORTSE HT = new Httptransportse (URL) of the WebService WSDL document; try {//(5) Use the call method to invoke the WebService method Ht.call (null, envelope),//(6) Use the GetResponse method to obtain the return result of the WebService method if (Envelope.getresponse ()! = null) {System.out.println (Envelope.getresponse ()); result = String.valueof (Envelope.getresponse ());// Toast.maketext (mainactivity.this, result, Toast.length_short)//.show ();}} catch (Exception e) {e.printstacktrace ();} return result;}}



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.