项目聊天功能中,需要监听图片的下载进度。类型于QQ的聊天图片查看。 当退出查看界面时, 下载进程仍在后台运行,再次进入查看界面,如何监听到图片的下载进度呢。 如图
/**
* 下载文件
*
* @param url
* @param outputStream 输出流
* @param onUpdateListener 下载进度监听
* @return
*/
public boolean downLoadFile(String url, OutputStream outputStream, OnUpdateListener onUpdateListener) {
if (StringUtils.isStrEmpty(url)) {
return false;
}
if (onUpdateListener != null) {
downloadObserver.put(url, onUpdateListener);
}
HttpGet get = new HttpGet(url);
// Header headerRange = new BasicHeader("connection", "close");
// get.addHeader(headerRange);
get.addHeader("connection", "close");
InputStream in = null;
try {
HttpResponse response = getDownloadClient(url).execute(get);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity he = response.getEntity();
if (onUpdateListener != null) {
onUpdateListener.onTotal(he.getContentLength());
}
in = he.getContent();
byte[] buffer = new byte[1024];
int len = 0;
long total = 0;
while ((len = in.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
if (onUpdateListener != null) {
onUpdateListener.onProcess(total);
}
}
return true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null)
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
这是原来 的下载代码, 这里的监听只能在第一次进放查看页面时生效。那么如何在重新进入时仍然能监听到下载的进度呢。 这里借鉴到监听者模式的思想。使用一个集合来管理 监听者对象
private Map<String, OnUpdateListener> downloadObserver = new HashMap<String, OnUpdateListener>();
提供添加监听的方法, 一个url对应一public void addObserver(String url, OnUpdateListener onUpdateListener) {
if (onUpdateListener != null) {
downloadObserver.put(url, onUpdateListener);
onUpdateListener.onTotal(-1);
}
}的 Listener动态获取
/**
* 下载文件
*
* @param url
* @param outputStream 输出流
* @param onUpdateListener 下载进度监听
* @return
*/
public boolean downLoadFile(String url, OutputStream outputStream, OnUpdateListener onUpdateListener) {
if (StringUtils.isStrEmpty(url)) {
return false;
}
if (onUpdateListener != null) {
downloadObserver.put(url, onUpdateListener);
}
HttpGet get = new HttpGet(url);
// Header headerRange = new BasicHeader("connection", "close");
// get.addHeader(headerRange);
get.addHeader("connection", "close");
InputStream in = null;
try {
HttpResponse response = getDownloadClient(url).execute(get);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity he = response.getEntity();
if (downloadObserver.get(url) != null) {
downloadObserver.get(url).onTotal(he.getContentLength());
}
in = he.getContent();
byte[] buffer = new byte[1024];
int len = 0;
long total = 0;
while ((len = in.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
if (downloadObserver.get(url) != null) {
total += len;
downloadObserver.get(url).onProcess(total);
}
}
return true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null)
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
这样,在任意地方都可以监听到子线程的下载进度。