項目聊天功能中,需要監聽圖片的下載進度。類型於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;
}
這樣,在任意地方都可以監聽到子線程的下載進度。