FlushedInputStream:Android下InputStream发生网络中断时的解决办法

来源:互联网 发布:android 打开淘宝链接 编辑:程序博客网 时间:2024/06/10 23:39

原文地址:http://blog.sina.com.cn/s/blog_5da93c8f0101phs9.html


但是BitmapFactory类的decodeStream方法在网络超时或较慢的时候无法获取完整的数据.这是因为google对于InputStream流有个小bug,
在慢速网络的情况下可能产生中断。我们可以考虑重写FilterInputStream处理skip方法来解决这个bug。
这里我们通过继承FilterInputStream类的skip方法来强制实现flush流中的数据,
主要原理就是检查是否到文件末端,告诉http类是否继续。


使用Http下载网络图片时,我们经常会这么实现:

static Bitmap downloadBitmap(String url) {
final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
inputStream = entity.getContent();
final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {

// 可以在这里提供更多更详细的关于IOException和IllegalStateException的错误信息

getRequest.abort();
Log.w("ImageDownloader", "Error while retrieving bitmap from " + url + e.toString());
} finally {
if (client != null) {
client.close();
}
}
return null;
}

但是BitmapFactory类的decodeStream方法在网络超时或较慢的时候无法获取完整的数据.这是因为google对于InputStream流有个小bug,
在慢速网络的情况下可能产生中断。我们可以考虑重写FilterInputStream处理skip方法来解决这个bug。
这里我们通过继承FilterInputStream类的skip方法来强制实现flush流中的数据,
主要原理就是检查是否到文件末端,告诉http类是否继续。

Android

static class FlushedInputStream extends FilterInputStream {
public FlushedInputStream(InputStream inputStream) {
super(inputStream);
}

@Override
public long skip(long n) throws IOException {
long totalBytesSkipped = 0L;
while (totalBytesSkipped < n) {
long bytesSkipped = in.skip(n - totalBytesSkipped);
if (bytesSkipped == 0L) {
int byte = read();
if (byte < 0) {
break; // we reached EOF
} else {
bytesSkipped = 1; // we read one byte
}
}
totalBytesSkipped += bytesSkipped;
}
return totalBytesSkipped;
}
}

通过FlushedInputStream(inputStream)替代BitmapFactory.decodeStream方法来可以有效解决慢网速下的数据量读取问题。

参考:http://bbs.9ria.com/thread-199455-1-1.html

0 0
原创粉丝点击