Android应用程序内存泄漏?

时间:2013-01-21 19:24:55

标签: android json memory-leaks

我有一个简单的Android应用程序,它从本地服务器上的php文件中读取一些JSON数据。它很简单,直到大约一个小时前,它工作正常。但是,经过一段时间的休息后(我甚至没有关闭我的电脑),虽然我不是这方面的专家,但它突然陷入了内存泄漏的困境。

我不确定为什么突然发生这种情况,因为我没有更改任何代码。但是当我运行应用程序时,我的logcat慢慢开始填充这样的消息:

“GC_CONCURRENT获释,910K,53%免费3167K / 6727K ......”

该应用程序最终运行,但仅在等待约1-2分钟后。无论如何,我想知道是否有人可以查看我的代码或告诉我可能导致这种情况发生的原因。

public static JSONArray getJSONfromURL(String url) {

    // initialize
    InputStream is = null;
    JSONArray jArray = null;
    String result = "";

    // http post
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
    }

    // convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "utf-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();

    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jArray = new JSONArray(result);         
    } catch (JSONException e) {
        Log.e("log_tag", "Error parsing data " + e.toString());
    }

    return jArray;
}

JSON数据根本不是很大。

感谢您的任何建议。

2 个答案:

答案 0 :(得分:2)

BufferedReader reader = new BufferedReader(new InputStreamReader(
            is, "utf-8"), 8);

您已经分配了8个字节的缓冲区大小。这非常小。除非你真的知道你在做什么,否则只需使用替代单参数构造函数的默认大小:

public BufferedReader(Reader in)

答案 1 :(得分:0)

好吧,我把'While'循环更改为了这个并且性能大幅提升:

int len;
char[] chars = new char[4*1024];
while((len = reader.read(chars))>=0) {
sb.append(chars, 0, len);
}

它仍然比我想要的慢,但至少我正朝着正确的方向前进。我将继续努力。谢谢大家。

相关问题