如何在我的应用程序中重用其余的连接类?

时间:2013-06-26 16:52:09

标签: android multithreading rest

我一直试图在这里找到答案,但我觉得所提出的问题都没有帮助我。

我正在开发一款不断维护和更改的Android应用程序。它还将使用大量的休息服务。在iOS中,我设法创建了一个处理连接的连接类,它接收的所有内容都是它调用的服务的名称以及调用特定服务所需的参数。它很容易维护,因为所有连接代码都在这个单独的类中。我试图在Android中做同样的事情,但由于线程(我正在使用AsyncTask),我真的很难。我对Android开发很新,所以请原谅我,如果我正在做一些非常愚蠢的事情,或者我只是不知道一些能帮助我解决这个问题的android对象。

这是我的MainActivity的代码,称为“连接类”

public void submitLogin(View view){
    RestHandler rh=new RestHandler();
    rh.mainActivity=this;
    int connection = rh.checkConnection(this);
    if(connection!=0){
        /*GetServiceTask task = new GetServiceTask();
        task.execute(new String []{"http://httpbin.org/ip","http://httpbin.org/get"});*/
        rh.performServiceWithData(true, "http://httpbin.org/get");
    }else{
        new AlertDialog.Builder(this).setTitle(R.string.popup_info).setMessage(R.string.error_network).setNeutralButton(R.string.accept, null).show();
    }

}

public void success(String result){

    new AlertDialog.Builder(this).setTitle(R.string.popup_info).setMessage("success: " + result).setNeutralButton(R.string.accept, null).show();

}

这是“连接类”的代码

public class RestHandler{

private HttpClient client;
private HttpPost httPost;
private HttpGet httpGet;
private HttpResponse response;
private HttpEntity entity;
private InputStream inputStream;
private BufferedReader reader;
private StringBuilder stringBuilder;
private String line;
private String result;
private String finalResult="UNMODIFIED";
MainActivity mainActivity;

public String performServiceWithData(boolean isGet, String url){
    if(isGet){
        GetServiceTask task = new GetServiceTask();
        task.execute(new String[]{url});
    }else{
        PostServiceTask task = new PostServiceTask();
        task.execute(new String[]{url});
    }
    return finalResult;
}

private class GetServiceTask extends AsyncTask<String, Void, String>{
    protected String doInBackground(String... services) {
          String response = "";           
          for(String service:services){
              response=response + "\n" + sendGet(service);
          }

          return response;
        }
    protected void onPostExecute(String result) {
            finalResult = result;
            mainActivity.success(finalResult);
        }
}

private class PostServiceTask extends AsyncTask<String, Void, String>{
    protected String doInBackground(String... services) {
          String response = "";
          RestHandler rh=new RestHandler();
          for(String service:services){
              response=response + "\n" + sendPost(service, null);
          }

          return response;
        }
    protected void onPostExecute(String result) {
            finalResult = result;
        }
}

public String sendGet(String path) {

    try {
        client = new DefaultHttpClient();
        httpGet = new HttpGet(path);
        response = client.execute(httpGet);
        entity = response.getEntity();
        inputStream = entity.getContent();
        reader = new BufferedReader(new InputStreamReader(inputStream));
        stringBuilder = new StringBuilder();
        line = "";
        result = "";
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line + "\n");
        }
        result = stringBuilder.toString();
        inputStream.close();
        return result;
    } catch (Exception e) {
        result = e.toString();
        return null;
    }

}

public String sendPost(String path, List nameValuePairs) {
    try {
        client = new DefaultHttpClient();
        stringBuilder = new StringBuilder(path);
        httPost = new HttpPost(stringBuilder.toString());
        httPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        response = client.execute(httPost);
        entity = response.getEntity();
        inputStream = entity.getContent();
        reader = new BufferedReader(new InputStreamReader(inputStream));
        stringBuilder = new StringBuilder();
        line = "";
        result = "";
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line + "\n");
        }
        result = stringBuilder.toString();
        inputStream.close();
        return /*"sendPost correct " +*/ result;
    } catch (Exception e) {
        return "sendPost exception " + e.toString();
    }

}

public int checkConnection(Activity activity) {
    int connectionType=0;
    /* connectionType 0 --> no connection
     * connectionType 1 --> wifi
     * connectionType 2 --> cell network*/
    ConnectivityManager cm = (ConnectivityManager) activity
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] info = cm.getAllNetworkInfo();
    for (NetworkInfo ni : info) {
        if (ni.getTypeName().equalsIgnoreCase("wifi"))
            if (ni.isConnected())
                connectionType=1;
        if (ni.getTypeName().equalsIgnoreCase("mobile"))
            if (ni.isConnected())
                connectionType=2;
    }
    return connectionType;
}

}

这段代码可以工作但是我想做一些类似于我可以在我的应用程序中的任何活动使用的东西,这个我开发的例子只有作用,因为我使用MainActivity作为连接类中的对象。

关于如何制作类似但独立于课程的任何建议?应该在每个Activity中执行asyncTask而不是“Connection”类吗?

顺便说一句,对不起我的英文:)

1 个答案:

答案 0 :(得分:0)

在调用服务的所有活动中重用您的RestHandler类实现简单回调接口:

public interface IRestCallback
{
  void onSuccess(String result);
}

public class MainActivity extends FragmentActivity implements ICallback
{
  ...
  void onSuceess(String result)
  {
    // process result
  }
  public void submitLogin(View view)
  {
    RestHandler rh=new RestHandler();
    rh.mainActivity=this;
    ...
  }
}

public class RestHandler {
  ...
  IRestCallback mainActivity;
}