【发布时间】:2010-03-31 02:26:10
【问题描述】:
我这里有一个从远程服务器下载数据到文件的功能。我仍然对我的代码没有信心。我的问题是,如果在读取流并将数据保存到文件时突然我在互联网上断开连接,下面的这些捕获异常真的可以捕获这种事件吗?如果没有,您能否建议如何处理此类事件?
注意:我在一个线程中调用这个函数,这样 UI 就不会被阻塞。
public static boolean getFromRemote(String link, String fileName, Context context){
boolean dataReceived = false;
ConnectivityManager connec = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connec.getNetworkInfo(0).isConnected() || connec.getNetworkInfo(1).isConnected()){
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(link);
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, 30000);
HttpConnectionParams.setSoTimeout(params, 30000);
HttpResponse response;
response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200){
HttpEntity entity = response.getEntity();
InputStream in = null;
OutputStream output = null;
try{
in = entity.getContent();
String secondLevelCacheDir = context.getCacheDir() + fileName;
File imageFile = new File(secondLevelCacheDir);
output= new FileOutputStream(imageFile);
IOUtilities.copy(in, output);
output.flush();
} catch (IOException e) {
Log.e("SAVING", "Could not load xml", e);
} finally {
IOUtilities.closeStream(in);
IOUtilities.closeStream(output);
dataReceived = true;
}
}
}catch (SocketTimeoutException e){
//Handle not connecting to client !!!!
Log.d("SocketTimeoutException Thrown", e.toString());
dataReceived = false;
} catch (ClientProtocolException e) {
//Handle not connecting to client !!!!
Log.d("ClientProtocolException Thrown", e.toString());
dataReceived = false;
}catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
dataReceived = false;
Log.d("MalformedURLException Thrown", e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
dataReceived = false;
Log.d("IOException Thrown", e.toString());
}
}
return dataReceived;
}
【问题讨论】:
标签: java android exception-handling