通过以下Android代码,我连接到互联网上的html页面并提取几行。代码在大多数情况下执行良好,但有时会挂起。我必须按下手机上的后退按钮才能获得“强制关闭”对话框。它总是在模拟器上运行良好(在PC上有快速连接)。
请帮忙。
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();
}
}
答案 0 :(得分:0)
您是否在应用程序的主线程中运行此操作?较长的运行进程应在单独的线程中执行,以避免减慢用户的主线程速度。
例如,请参阅Android Developer guide。