2013-10-30 43 views
0

我有一个Web服务类来调用我的Web方法。但是这必须在AsyncTask类中调用。目前我的所有活动中都有一个AsyncTask类来调用我的Web服务方法。是否有可能将它们(Web服务类和AsyncTask)混合成一个Web服务类,它取得Web方法的名称并在执行后返回结果?如何让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

代替的AsyncTask考虑AsyncQueryHandler类 – pskink

回答

0

我建议添加方法添加到WebService类为每个webservice方法,并从调用Activity传入一个侦听器,然后在onPostExecute中调用该侦听器。

然后,您可以从您的活动叫WebService.doThings(thingsListener),用相应的方法执行的AsyncTask,并在所提供的监听器,结果反应...

0

当我面临同样的问题,我所做的:

  1. 将所有API调用实现为static方法。他们以同步方式被呼叫
  2. IntentService后裔,谁调用API然后
  3. IntentService作为intent广播结果。有兴趣的活动,认购活动从这个IntentService

为了使活动独立于网络操作,可以考虑使用一个数据库,一个ContentProvider或一些其他的存储机制,所以可能需要等这种方法将花费你一些LoaderManager所有好处时间,但架构将从中受益。

+0

在这种情况下,最好是ContentProvider的与AsyncQueryHandler结合起来,这样不仅查询执行异步,而且更新,删除和插入 – pskink

+0

您可以通过实现匿名接口获取此信息这将在doInbackground中返回结果。 –