在Android中为慢速网络调用httpClient.execute时应用程序崩溃

时间:2013-04-03 09:21:46

标签: java android http

我正在使用此方法检查网络状态:

public boolean hasConnection() {
    ConnectivityManager cm = (ConnectivityManager) SigninActivity.this
            .getBaseContext()
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo wifiNetwork = cm
            .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (wifiNetwork != null && wifiNetwork.isConnected()) {
        return true;
    }

    NetworkInfo mobileNetwork = cm
            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    if (mobileNetwork != null && mobileNetwork.isConnected()) {
        return true;
    }

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null && activeNetwork.isConnected()) {
        return true;
    }

    return false;
}

然后使用此类为json调用for web服务:

    public class JSONParser {

InputStream is = null;
JSONObject jObj = null;
String json = "";
HttpClient httpClient;

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url) {

    // Making HTTP request
    try { // defaultHttpClient DefaultHttpClient
        httpClient = new DefaultHttpClient();

        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        reader.close();
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}
    }

但是,对于非常慢的网络而言,应用程序正在崩溃,因为在正常情况下工作效果很好。任何人都可以提出更好的方法来避免强制关闭吗?

“我是从AsyncTask类doInBackground方法调用此类的。 提前致谢

0 个答案:

没有答案