Java代码
- viewplaincopytoclipboardprint?
- viewplaincopytoclipboardprint?
- packagenet.blogjava.mobile.wsclient;
- importorg.ksoap2.SoapEnvelope;
- importorg.ksoap2.serialization.SoapObject;
- importorg.ksoap2.serialization.SoapSerializationEnvelope;
- importorg.ksoap2.transport.HttpTransportSE;
- importandroid.app.Activity;
- importandroid.os.AsyncTask;
- importandroid.os.Bundle;
- importandroid.view.View;
- importandroid.view.View.OnClickListener;
- importandroid.widget.Button;
- importandroid.widget.EditText;
- importandroid.widget.TextView;
- publicclassMainextendsActivityimplementsOnClickListener
- {
- privateEditTextetProductName;
- privateTextViewtvResult;
- classWSAsyncTaskextendsAsyncTask
- {
- Stringresult="";
- @Override
- protectedObjectdoInBackground(Object...params)
- {
- try
- {
- StringserviceUrl="http://192.168.17.156:8080/axis2/services/SearchProductService?wsdl";
- StringmethodName="getProduct";
- SoapObjectrequest=newSoapObject("http://service",
- methodName);
- request.addProperty("productName",etProductName.getText().toString());
- SoapSerializationEnvelopeenvelope=newSoapSerializationEnvelope(
- SoapEnvelope.VER11);
- envelope.bodyOut=request;
- HttpTransportSEht=newHttpTransportSE(serviceUrl);
- ht.call(null,envelope);
- if(envelope.getResponse()!=null)
- {
- SoapObjectsoapObject=(SoapObject)envelope.getResponse();
- result="产品名称:"+soapObject.getProperty("name")+"\n";
- result+="产品数量:"+soapObject.getProperty("productNumber")
- +"\n";
- result+="产品价格:"+soapObject.getProperty("price");
- }
- else
- {
- result="无此产品.";
- }
- }
- catch(Exceptione)
- {
- result="调用WebService错误.";
- }
- //必须使用post方法更新UI组件
- tvResult.post(newRunnable()
- {
- @Override
- publicvoidrun()
- {
- tvResult.setText(result);
- }
- });
- returnnull;
- }
- }
- @Override
- publicvoidonClick(Viewview)
- {
- //异步执行调用WebService的任务
- newWSAsyncTask().execute();
- }
- @Override
- publicvoidonCreate(BundlesavedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- ButtonbtnSearch=(Button)findViewById(R.id.btnSearch);
- btnSearch.setOnClickListener(this);
- etProductName=(EditText)findViewById(R.id.etProductName);
- tvResult=(TextView)findViewById(R.id.tvResult);
- }
- }
1. 一般需要编写一个AsyncTask的子类来完成后台执行任务的工作。
2. AsyncTask的核心方法是doInBackground,当调用AsyncTask类的execute方法时,doInBackground方法会异步执行。因此,可以将执行任务的代码写在doInBackground方法中。
3.由于本例中的TextView组件是在主线程(UI线程)中创建的,因此,在其他的线程(doInBackground方法所在的线程)中不能直接更新TextVew组件。为了更新TextView组件,需要使用TextView类的post方法。该方法的参数是一个Runnable对象,需要将更新TextView组件的代码写在Runnable接口的run方法中。
4.虽然不能在其他线程中更新UI组件,但可以从其他线程直接读取UI组件的值。例如,在doInBackground方法中直接读取了EditText组件的值。
5.调用AsyncTask类的execute方法后会立即返回。execute方法的参数就是doInBackground方法的参数。doInBackground方法的返回值可以通过AsyncTask.execute(...).get()方法获得。
读者可以将本例中的IP改成其他的值,看看单击按钮后,是否还可在文本框中输入其他的内容。如果这个IP是正确的,并且WebService可访问,那么会在TextView组件中输出相应的返回值。