Android platform invoke Web Service: threading introduced

Source: Internet
Author: User

Connect to the above

Legacy Issues

If this code is not available in the OnCreate method of mainactivity:

Forces the operation of Strictmode.setthreadpolicy (New StrictMode.ThreadPolicy.Builder ()       . Detectdiskreads () in the UI thread. Detectdiskwrites (). Detectnetwork ().        Penaltylog (). build ());           Strictmode.setvmpolicy (New StrictMode.VmPolicy.Builder ().       detectleakedsqlliteobjects (). Penaltylog (). Penaltydeath ()        . Build ());

will report The error is as follows:

FATAL Exception:main

Java.lang.NullPointerException

Atcom.example.demoservice.MainActivity.getRemoteInfo (mainactivity.java:91)

Atcom.example.demoservice.mainactivity$1.onclick (mainactivity.java:51)

this is because Android 3.0+ above has not been recommended to add time-consuming operations to the activity, to interface and data detachment. More than 4.0 of the communication must be put into the thread to do , not on the UI thread. The workaround is another thread , and if you want to work on the UI thread, you need to add the code as above .

Obviously this is undesirable, because the communication consumes a long time, may let the user foolishly waits, then then by introduces the thread to solve this problem.


Creating threads from the Runnable interface and the thread class

we can use the Runnable interface and the thread class to create threads that discard forced use UI the main thread of the way, the code is as follows (while the code is organized, the NameSpace and other variables to be extracted)

Public Classmainactivity extends Activity {public static final String TAG = "WEBSERVICE_PJ";     Private EditText Phonesecedittext;     Private TextView Resultview;      Private Button Querybutton; @Override public void OnCreate (bundlesavedinstancestate) {//Strictmode.setthreadpolicy (newstric TMode.ThreadPolicy.Builder ()//. Detectdiskreads (). Detectdiskwrites (). Detectnetwork ()//. Penaltylog (). Build ()) ;////Strictmode.setvmpolicy (NewStrictMode.VmPolicy.Builder ()//. Detectleakedsqlliteobjects (). penaltyl          OG (). Penaltydeath ()//. Build ());        Super.oncreate (savedinstancestate);          Setcontentview (R.layout.activity_main);         Phonesecedittext = (EditText) Findviewbyid (R.ID.PHONE_SEC);         Resultview = (TextView) Findviewbyid (R.id.result_text);          Querybutton = (Button) Findviewbyid (R.ID.QUERY_BTN); Querybutton.setonclicklistener (Newonclicklistener () {@Override public void OnClick (View v) {log.i (TAG, "Mainactivity thread ID:" +thread.currentthread (). GetId ());                 Mobile number (segment) String phonesec =phonesecedittext.gettext (). toString (). Trim (); Simple to determine whether the user entered the mobile phone number (segment) is legal if ("". Equals (phonesec) | | Phonesec.length () < 7) {//Give error Phonesecedittext.seterror ("You entered the mobile number (segment) is wrong!                    ");                     Phonesecedittext.requestfocus ();                     The TextView that displays the results of the query is emptied Resultview.settext ("");                 Return                 }//namespace String nameSpace = "http://WebXml.com.cn/";                 The method name called String methodName = "Getmobilecodeinfo";                 EndPoint String EndPoint = "Http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx"; SOAP Action String soapaction = "http://WebXml.Com.cn/getmobilecodeinfo ";                Method params and Values arraylist<string> params= new arraylist<string> ();               Arraylist<object> vals =new arraylist<object> ();                Params.add ("Mobilecode");                Params.add ("UserId");                Vals.add (PHONESEC);                               Vals.add ("");                                                           Create a thread by Runnable interface and thread class call WebService Newmythread (Namespace,methodname,endpoint,soapaction,                       params,vals). Start ();             The results returned by WebService are displayed in TextView resultview.settext (GetResult ());     }         }); }//through Runnable interface and thread class, get thread return value privatestring result;     Publicstring GetResult () {returnresult;}    Private class MyThread extends thread{private String nameSpace;    Private String MethodName;    Private String EndPoint;        Private String SOAPAction; PrivateArraylist<string> params;           Private arraylist<object> Vals; Public MyThread (String nameSpace, String methodName, Stringendpoint, string soapaction, arraylist<st        Ring> params,arraylist<object> vals) {this.namespace = NameSpace;        This.methodname = MethodName;        This.endpoint = EndPoint;        This.soapaction = SOAPAction;        This.params = params;    This.vals = Vals; } @Overridepublicvoid Run () {log.i (TAG, "MyService thread ID:" +thread.currentthread (). GetId ()); result= Getremoteinfo ( NameSpace, MethodName, EndPoint, soapaction,params,vals);} }/** * @MethodName: Getremoteinfo * @Description: Call remote WebService method * @param Namespa CE * @param methodName * @param endPoint * @param soapaction * @param params * @param vals * @retu                     RN */public string Getremoteinfo (Stringnamespace, String methodName,              Stringendpoint, String SOAPAction, arraylist<string> params, Arrayli St<object>vals) {//Specify WebService namespace and method name called Soapobject RPC = Newsoapobject (NameSpace, MethodName          ); Set the two parameters that need to be passed in to call the WebService interface Mobilecode, userId for (int i = 0; i < params.size (); i++) {Rpc.addproperty (params.ge          T (i), vals.get (i));} Generates SOAP request information that calls the WebService method and specifies the version of Soap Soapserializationenvelope envelope =new soapserializationenvelope (soapenvel Ope.          VER10);         Envelope.bodyout = RPC;         Sets whether to invoke the DotNet developed by webservice//envelope.dotnet = true;         Equivalent to envelope.bodyout = RPC;          Envelope.setoutputsoapobject (RPC);         Httptransportse transport = Newhttptransportse (EndPoint);         try {//Call WebService Transport.call (Soapaction,envelope);         } catch (Exception e) {e.printstacktrace (); }//Gets the returned data soapobjectObject = (soapobject) Envelope.bodyin;        String result = "";         if (Object! = NULL) {//Gets the results returned by result =object.getproperty (0). toString ();    } return result;  } }


Communicate through threads to get the same results



A new problem arises

It can be found that the execution thread needs to return a value in the threads, by saving the return value in Run (), the variable that stores the return value should be a member variable of mainactivity, and then the value is obtained in the main thread with a GET method.

But when the run is done is unknown, it is likely that the first click of the button will still not see the results until the second or more to see, so we need a certain mechanism to ensure.

and in Java SE5 began to use callable and Future to manage multithreading, you can solve this problem, next ...


Source Download

http://download.csdn.net/detail/tcl_6666/7365341


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.