如何使用AsyncTask处理同一类中Web服务的不同方法调用?

时间:2015-02-10 19:51:58

标签: java android web-services android-asynctask

我正在开发一款Android应用,它应该连接到网络服务并将数据保存到应用的本地数据库中。我使用AsyncTask从我的"登录"连接到所述Web服务。 class,然后将结果返回到"登录中的processFinish方法。"问题是我需要在Web服务中分​​离几个方法带来的数据,据我所知,结果总是由processFinish处理。这是一个问题,因为我需要根据我调用的方法不同地处理数据。

有没有办法告诉processFinish我调用的Web服务中的哪个方法,所以它能以不同的方式处理结果?我考虑过从Web服务本身发送方法的名称作为结果的一部分,但它感觉很有用,我希望以更清洁的方式做到这一点。

以下是我使用的代码:

LoginActivity.java(缩写):

public class LoginActivity extends ActionBarActivity implements AsyncResponse {

    public static DBProvider oDB;
    public JSONObject jsonObj;

    public JSONObject jsonUser;

    WebService webService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        oDB = new DBProvider(this);
    }
    /*Function that validates user and password (on button press).*/
    public void validateLogin(View view){

        ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

        if (!isConnected){
            Toast.makeText(this, "No connection!", Toast.LENGTH_LONG).show();
        }else{

            /* params contains the method's name and parameters I send to the web service. */
            String[][][] params = {
                {
                    {"MyWebServiceMethod"}
                },
                {
                    {"user", "myUserName", "string"},
                    {"pass", "myPass", "string"}
                }
            };

            try{
                webService = new WebService();
                webService.delegate = this;
                webService.execute(params);
            }catch(Exception ex){
                Toast.makeText(this, "Error!: " + ex.getMessage(), Toast.LENGTH_LONG).show();
            }
        }

    }

    public void processFinish(String result){
        try{
            // Here I handle the data in "result"

            }
        }catch(JSONException ex){
            Toast.makeText(this, "JSONException: " + ex.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

}

WebService.java:

public class WebService extends AsyncTask<String[][][], Void, String> {

    /**
     * Variable Declaration................
     * 
     */
    public AsyncResponse delegate = null;
    String namespace = "http://example.net/";
    private String url = "http://example.net/WS/MyWebService.asmx";

    public String result;

    String SOAP_ACTION;
    SoapObject request = null, objMessages = null;
    SoapSerializationEnvelope envelope;
    HttpTransportSE HttpTransport;

    /**
     * Set Envelope
     */
    protected void SetEnvelope() {

        try {
            // Creating SOAP envelope
            envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

            //You can comment that line if your web service is not .NET one.
            envelope.dotNet = true;

            envelope.setOutputSoapObject(request);
            HttpTransport = new HttpTransportSE(url);
            HttpTransport.debug = true;

        } catch (Exception e) {
            System.out.println("Soap Exception---->>>" + e.toString()); 
        }
    }

    @Override
    protected String doInBackground(String[][][]... params) {
        // TODO Auto-generated method stub
        try {
            String[][][] data = params[0];

            final String methodName = data[0][0][0];
            final String[][] arguments = data[1];

            SOAP_ACTION = namespace + methodName;

            //Adding values to request object
            request = new SoapObject(namespace, methodName);

            PropertyInfo property;

            for(int i=0; i<arguments.length; i++){
                property = new PropertyInfo();
                property.setName(arguments[i][0]);
                property.setValue(arguments[i][1]);

                if(arguments[i][2].equals("int")){
                    property.setType(int.class);
                }
                if(arguments[i][2].equals("string")){
                    property.setType(String.class);
                }
                request.addProperty(property);
            }

            SetEnvelope();

            try {
                //SOAP calling webservice
                HttpTransport.call(SOAP_ACTION, envelope);

                //Got Webservice response
                result = envelope.getResponse().toString();

            } catch (Exception e) {
                // TODO: handle exception
                result = "Catch1: " + e.toString() + ": " + e.getMessage();
            }
        } catch (Exception e) {
            // TODO: handle exception
            result = "Catch2: " + e.toString();
        }

        return result;
    }

    @Override
    protected void onPostExecute(String result) {
        delegate.processFinish(result);
    }
    /************************************/
}

AsyncResponse.java:

public interface AsyncResponse {
    void processFinish(String output);
}

1 个答案:

答案 0 :(得分:1)

您可以使用不同的AsyncResponse课程。匿名类使这更方便:

// in one place
webService.delegate = new AsyncResponse() {
    @Override
    void processFinish(String response) {
        // do something
    }
};

// in another place
webService.delegate = new AsyncResponse() {
    @Override
    void processFinish(String response) {
        // do something else
    }
};