我有一个小型 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());
}
最佳答案
您是从 Activity 还是从服务运行它?在我自己的应用程序中,如果我从服务运行代码,我只会遇到这个问题;它在 wifi 上运行完美,但在 3G 上崩溃,并且从不在 Activity 中崩溃。
我能找到的唯一修复服务崩溃的方法如下:
- 如果在 wifi 上,并且使用服务,请使用 AsyncTask
- 如果在 3G 上,并且使用服务,则在主线程上运行
- 否则使用AsyncTask
希望这对您有所帮助。
关于Android 应用程序在 3G 慢速连接时崩溃,但在 wifi 上工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6084648/