Android应用程序在3G慢速连接时崩溃但在wifi上工作正常

时间:2011-05-21 21:44:17

标签: android

我有一个小型Android应用程序,基本上执行http调用以检索一些网页信息并在本地解析它以用于显示目的。

在wifi上工作正常。但是,在提交http查询后,应用程序在3G上时会随机崩溃(不是所有时间,但经常足够)。通常我只能重新启动应用程序,尝试执行相同的任务,它将按预期工作。我有点试图调试这个问题。它是由慢速互联网连接引起的吗?丢包?我可以在那里放什么样的检查代码来防止这种情况发生?

一些示例代码:

    HttpClient client = new DefaultHttpClient();
    HashMap<String, String[]> hmSearchResults = null;       
    HttpGet getMethod = new HttpGet(url);

    try {

        ResponseHandler<String> responseHandler = new BasicResponseHandler();

        String resultPage = client.execute(getMethod, responseHandler);

        // I am think the error is here if resultPage == null due to 
        // whatever reason, is there any check I can put around 
        // client.execute?
        hmSearchResults = ParseHtml.getSearchResultText(resultPage, numRequestResults);

    } catch (Throwable t) {     
        Utility.showToast(this,"Request failed: " + t.toString());
    }

1 个答案:

答案 0 :(得分:0)

您是从活动还是通过服务运行此操作?在我自己的应用程序中,如果我从服务运行代码,我只会遇到此问题;它在wifi上完美运行,但在3G上崩溃,并且从不在活动中崩溃。

我找到修复服务崩溃的唯一解决办法如下:

  • 如果在wifi上并使用服务,请使用AsyncTask
  • 如果使用3G,并使用服务,则在主线程上运行
  • 否则使用AsyncTask

希望这有帮助。

相关问题