我的 Android 应用程序会向 URL 发送 http 帖子,例如http://example.com/[电子邮件受保护] http://example.com/abc.php?email=abc@xyz.com因此,Android 应用程序基本上与服务器端的 PHP 进行通信,接收 JSON 响应并解析它们以填充应用程序中的各种视图。工作正常。
我的问题是 - 我应该如何处理 Android 应用程序中的以下事件,以便万一这些事件发生在服务器端应用程序中,应用程序不应该像现在一样强制关闭。
服务器超时,未收到响应。应用程序强制现已关闭。我想妥善处理这件事。
作为对应用程序 http post 到服务器的响应而返回的错误代码。由于我尚未处理此问题,应用程序力量目前已关闭。
我遇到过这两种情况,其中应用程序未编码来处理这些事件。请随意添加可能发生的任何其他事件,这些事件可能会导致 Android 应用程序中发生 ANR。
一些代码片段或线索会对我有很大帮助,因为我以前从未这样做过。
Thanks.
添加到目前为止非常好的建议......
我的工作同事教我使用 org.apache.http 包中的类,如下所示:
String result = null;
HttpGet request = new HttpGet(some_uri);
// As Jeff Sharkey does in the android-sky example,
// use request.setHeader to optionally set the User-Agent header.
HttpParams httpParams = new BasicHttpParams();
int some_reasonable_timeout = (int) (30 * DateUtils.SECOND_IN_MILLIS);
HttpConnectionParams.setConnectionTimeout(httpParams, some_reasonable_timeout);
HttpConnectionParams.setSoTimeout(httpParams, some_reasonable_timeout);
HttpClient client = new DefaultHttpClient(httpParams);
try
{
HttpResponse response = client.execute(request);
StatusLine status = response.getStatusLine();
if (status.getStatusCode() == HttpStatus.SC_OK)
{
ResponseHandler<String> responseHandler = new BasicResponseHandler();
result = responseHandler.handleResponse(response);
}
else
{
// Do something else, if wanted.
}
}
catch (ClientProtocolException e)
{
Log.e(LOG_TAG, "HTTP Error", e);
// Do something else, if wanted.
}
catch (IOException e)
{
Log.e(LOG_TAG, "Connection Error", e);
// Do something else, if wanted.
}
finally
{
client.getConnectionManager().shutdown();
}
// Further parse result, which may well be JSON.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)