我在一些客户的手机上遇到了一个奇怪的问题。看来,在服务区域外停留数小时后,我的Android应用程序将失去访问网络的能力。其他应用程序(如Web浏览器或电子邮件)可以访问Web,但不能访问我的应用程序。
唯一可以想象的解释是,当没有数据服务时,它会以某种方式泄漏套接字。
这是我的代码:
String sendWebPOST(String url, String pPostData) throws IOException {
AndroidHttpClient c = null;
InputStream is = null;
OutputStream os = null;
int rc;
String strResponse = null;
try {
c = AndroidHttpClient.newInstance("Mobile");
// Set the request method and headers
HttpPost request = new HttpPost(url);
request.addHeader("Content-Type", "application/x-www-form-urlencoded");
request.setEntity(new StringEntity(pPostData));
try {
HttpResponse response = c.execute(request);
// Getting the response code will open the connection,
// send the request, and read the HTTP response headers.
// The headers are stored until requested.
rc = response.getStatusLine().getStatusCode();
if (rc != HttpStatus.SC_OK) {
throw new IOException("HTTP response code: " + rc);
}
try {
is = response.getEntity().getContent();
int ch;
StringBuffer sb = new StringBuffer();
while ((ch = is.read()) != -1) {
sb.append((char) ch);
}
//if(sb.length() > 0)
strResponse = sb.toString();
}
finally {
if (is != null) {
is.close();
}
}
}
finally {
if (os != null) {
os.close();
}
}
}
catch (ClassCastException e) {
throw new IllegalArgumentException("Not an HTTP URL");
}
finally {
if (c != null) {
c.close();
}
}
return strResponse;
}
此函数大约每十分钟调用一次,以便向远程服务器发送更新。当应用程序进入这种奇怪状态时,用户仍然可以打开活动,与菜单交互等,因此应用程序仍在运行。但是,它无法通过网络发送任何内容。
可能会发生什么想法?
有问题的手机是在T-Mobile网络上运行Android 2.3的myTouch 4G和三星Galaxy II。
感谢。
答案 0 :(得分:0)
出于某种原因,使用HttpURLConnection而不是AndroidHttpClient更好。一旦我升级了代码,我就不会再报告任何问题了。
HttpURLConnection conn = null;
InputStream is = null;
OutputStream os = null;
String strResponse = null;
try {
conn = (HttpURLConnection)(new URL(url)).openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "close");
conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
conn.setConnectTimeout(30000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setChunkedStreamingMode(0);
conn.connect();
os = new BufferedOutputStream(conn.getOutputStream());
os.write(pPostData.getBytes());
os.flush();
// Getting the response code will open the connection,
// send the request, and read the HTTP response headers.
// The headers are stored until requested.
int rc = conn.getResponseCode();
if (rc != HttpURLConnection.HTTP_OK) {
throw new IOException("HTTP response code: " + rc);
}
is = new BufferedInputStream(conn.getInputStream());
int ch;
StringBuffer sb = new StringBuffer();
while ((ch = is.read()) != -1) {
sb.append((char) ch);
}
//if(sb.length() > 0)
strResponse = sb.toString();
}
finally {
if (is != null) {
try {
is.close();
}
catch (Exception ex) {
System.out.println("is.close ex " + ex);
}
}
if (os != null) {
try {
os.close();
}
catch (Exception ex) {
System.out.println("os.close ex " + ex);
}
}
if (conn != null) {
try {
conn.disconnect();
}
catch (Exception ex) {
System.out.println("disconnect ex " + ex);
}
}
}