我有一个Web服务类来调用我的Web方法。但这必须在AsyncTask类中调用。目前,我在所有活动中都有一个AsyncTask类来调用我的Web服务方法。是否可以将它们(Web服务类和AsyncTask)混合为一个Web服务类,它采用Web方法的名称并在执行后返回结果?
这是我的网络服务类:
package ClassLibrary;
public class WebService {
private String namespace="";
private String url="";
public WebService(String namespace,String url) {
super();
this.namespace = namespace;
this.url = url;
}
public String CallMethod(String methodName,PropertyInfo pi) {
String result = "default";
SoapObject request = new SoapObject(namespace, methodName);
request.addProperty(pi);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(url);
try {
androidHttpTransport.call(namespace+methodName, envelope);
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
result= response.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
这就是我在AsyncTask中访问的方式:
private class AsyncCallWS extends AsyncTask<String, Void, Void> {
private ProgressDialog dialog;
private Activity activity;
public String wsOutput="";
public String methodName="";
private WebService ws;
public AsyncCallWS(Activity activity,String methodName) {
this.activity = activity;
this.dialog = new ProgressDialog(activity);
this.methodName = methodName;
}
@Override
protected Void doInBackground(String... params) {
ws = new WebService(PublicVariable.NAMESPACE, PublicVariable.URL);
PropertyInfo pi= new PropertyInfo();
pi.setName("UserID");
pi.setValue("1");
pi.setType(String.class);
wsOutput=ws.CallMethod("GetPersonalInfo", pi);
return null;
}
@Override
protected void onPostExecute(Void result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
if (methodName == "GetPersonalInfo") {
Log.d("Ehsan","OUTPUT IS:"+ wsOutput);
}
}
}
答案 0 :(得分:0)
我建议为每个webservice方法的WebService类添加(static?)方法,并从调用的Activity传入一个监听器,然后在onPostExecute中调用它。
然后,您可以从Activity调用WebService.doThings(thingsListener),使用相应的方法执行AsyncTask,并在提供的侦听器中对结果做出反应...
答案 1 :(得分:0)
当我遇到同样的问题时,我做了:
static
方法。 IntentService
后代,他打电话给api,然后是IntentService
将结果广播为意图。感兴趣的活动订阅此IntentService
要使活动独立于网络操作,请考虑使用数据库,ContentProvider
或其他一些存储机制,这样可能会带来LoaderManager
等所有好处。这种方法会花费您一些时间,但是建筑将从中受益匪浅。