通过以下一段 Android 代码,我连接到互联网上的一个 html 页面并提取了几行代码。代码大部分时间执行良好,但有时会挂起。我必须按手机上的后退按钮才能获得“强制关闭”对话框。它总是在模拟器上运行良好(在 PC 上具有快速连接)。
- 那么,代码挂起是因为我的手机上的 EDGE/GPRS 连接速度慢吗?
- 我应该插入套接字超时吗?
- 代码挂起还有什么其他原因?
- 如何防止代码挂起?有没有办法在重试之前捕获错误并向用户返回消息?
请帮忙。
private String readFile(){
List<String> scores = new ArrayList<String>();
String result="";
String score = "";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://www.espncricinfo.com/icc_cricket_worldcup2011/engine/current/match/433567.html");
try{
HttpResponse response = client.execute(request);
//txtResult.setText(HttpHelper.request(response));
try{
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
result = str.toString();
//result = str.toString().substring(1,500);
Pattern p = Pattern.compile(
"<title>(.*)</title>",
Pattern.DOTALL
);
Matcher matcher = p.matcher(
result
);
if (matcher.find())
{
score = matcher.group(1).toString();
}
TextView tv = (TextView)findViewById(R.id.textview);
tv.setText(score);
return score;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(this, "IOException e = " + e.toString(), Toast.LENGTH_LONG).show();
Log.d(TAG, "IOException e = " + e.toString());
return "IOException e = " + e.toString();
}catch(Exception ex){
result = "Error";
ex.printStackTrace();
Toast.makeText(this, "Exception ex = " + ex.toString(), Toast.LENGTH_LONG).show();
Log.d(TAG,"Exception ex = " + ex.toString());
return "Exception ex = " + ex.toString();
}
} catch (SocketTimeoutException e) {
e.printStackTrace();
Toast.makeText(this, "SocketTimeoutException e = " + e.toString(), Toast.LENGTH_LONG).show();
Log.d(TAG, "SocketTimeoutException e = " + e.toString());
return "SocketTimeoutException e = " + e.toString();
}catch(Exception ex){
Toast.makeText(this, "Exception ex1 = " + ex.toString(), Toast.LENGTH_LONG).show();
Log.d(TAG, "Exception ex1 = " + ex.toString());
return "Exception ex1 = " + ex.toString();
}
}