我一直试图在这里找到答案,但我觉得提出的问题都没有帮助我。
我正在开发一个将不断维护和更改的 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 作为连接类中的对象。
关于如何制作类似但独立于班级的任何建议?asyncTask 是否应该在每个 Activity 而不是“Connection”类中执行?
顺便说一句,对不起我的英语:)