概述java
對於客戶端——服務器端應用,從遠程獲取圖片算是常常要用的一個功能,而圖片資源每每會消耗比較大的流量,對應用來講,若是處理很差這個問題,那會讓用戶很崩潰,不知不覺手機流量就用完了,等用戶發現是你的應用消耗掉了他手機流量的話,那麼可想而知你的應用將面臨什麼樣的命運。android
另一個問題就是加載速度,若是應用中圖片加載速度很慢的話,那麼用戶一樣會等到崩潰。算法
那麼如何處理好圖片資源的獲取和管理呢?緩存
異步下載服務器
你們都知道,在android應用中UI線程5秒沒響應的話就會拋出無響應異常,對於遠程獲取大的資源來講,這種異常仍是很容易就會拋出來的,那麼怎麼避免這種問題的產生。在android中提供兩種方法來作這件事情:異步
具體的作法這裏就不介紹了,查下API就能夠了,或者是google、baidu下。這裏主要來講本地緩存。ide
本地緩存優化
對於圖片資源來講,你不可能讓應用每次獲取的時候都從新到遠程去下載(ListView),這樣會浪費資源,可是你又不能讓全部圖片資源都放到內存中去(雖然這樣加載會比較快),由於圖片資源每每會佔用很大的內存空間,容易致使OOM。那麼若是下載下來的圖片保存到SDCard中,下次直接從SDCard上去獲取呢?這也是一種作法,我看了下,仍是有很多應用採用這種方式的。採用LRU等一些算法能夠保證sdcard被佔用的空間只有一小部分,這樣既保證了圖片的加載、節省了流量、又使SDCard的空間只佔用了一小部分。另一種作法是資源直接保存在內存中,而後設置過時時間和LRU規則。google
sdcard保存:url
關鍵代碼:
/**
* 計算sdcard上的剩餘空間
* @return
*/
private int freeSpaceOnSd() {
StatFs stat = newStatFs(Environment.getExternalStorageDirectory() .getPath());
double sdFreeMB = ((double)stat.getAvailableBlocks() * (double) stat.getBlockSize()) / MB;
return (int) sdFreeMB;
}
/** * 修改文件的最後修改時間 * @param dir * @param fileName */ private void updateFileTime(String dir,String fileName) { File file = new File(dir,fileName); long newModifiedTime =System.currentTimeMillis(); file.setLastModified(newModifiedTime); }
/**
*計算存儲目錄下的文件大小,當文件總大小大於規定的CACHE_SIZE或者sdcard剩餘空間小於FREE_SD_SPACE_NEEDED_TO_CACHE的規定
* 那麼刪除40%最近沒有被使用的文件
* @param dirPath
* @param filename
*/
private void removeCache(String dirPath) {
File dir = new File(dirPath);
File[] files = dir.listFiles();
if (files == null) {
return;
}
int dirSize = 0;
for (int i = 0; i < files.length;i++) {
if(files[i].getName().contains(WHOLESALE_CONV)) {
dirSize += files[i].length();
}
}
if (dirSize > CACHE_SIZE * MB ||FREE_SD_SPACE_NEEDED_TO_CACHE > freeSpaceOnSd()) {
int removeFactor = (int) ((0.4 *files.length) + 1);
Arrays.sort(files, newFileLastModifSort());
Log.i(TAG, "Clear some expiredcache files ");
for (int i = 0; i <removeFactor; i++) {
if(files[i].getName().contains(WHOLESALE_CONV)) {
files[i].delete();
}
}
}
}
/**
* 刪除過時文件
* @param dirPath
* @param filename
*/
private void removeExpiredCache(StringdirPath, String filename) {
File file = new File(dirPath,filename);
if (System.currentTimeMillis() -file.lastModified() > mTimeDiff) {
Log.i(TAG, "Clear some expiredcache files ");
file.delete();
}
}
/**
* TODO 根據文件的最後修改時間進行排序 *
*/
classFileLastModifSort implements Comparator<File>{
public int compare(File arg0, File arg1) {
if (arg0.lastModified() >arg1.lastModified()) {
return 1;
} else if (arg0.lastModified() ==arg1.lastModified()) {
return 0;
} else {
return -1;
}
}
}
內存保存:
在內存中保存的話,只能保存必定的量,而不能一直往裏面放,須要設置數據的過時時間、LRU等算法。這裏有一個方法是把經常使用的數據放到一個緩存中(A),不經常使用的放到另一個緩存中(B)。當要獲取數據時先從A中去獲取,若是A中不存在那麼再去B中獲取。B中的數據主要是A中LRU出來的數據,這裏的內存回收主要針對B內存,從而保持A中的數據能夠有效的被命中。
private final HashMap<String, Bitmap>mHardBitmapCache = new LinkedHashMap<String, Bitmap>(HARD_CACHE_CAPACITY/ 2, 0.75f, true) {
@Override
protected booleanremoveEldestEntry(LinkedHashMap.Entry<String, Bitmap> eldest) {
if (size() >HARD_CACHE_CAPACITY) {
//當map的size大於30時,把最近不經常使用的key放到mSoftBitmapCache中,從而保證mHardBitmapCache的效率
mSoftBitmapCache.put(eldest.getKey(), newSoftReference<Bitmap>(eldest.getValue()));
return true;
} else
return false;
}
};
/**
*當mHardBitmapCache的key大於30的時候,會根據LRU算法把最近沒有被使用的key放入到這個緩存中。
*Bitmap使用了SoftReference,當內存空間不足時,此cache中的bitmap會被垃圾回收掉
*/
private final staticConcurrentHashMap<String, SoftReference<Bitmap>> mSoftBitmapCache =new ConcurrentHashMap<String,SoftReference<Bitmap>>(HARD_CACHE_CAPACITY / 2);
* 從緩存中獲取圖片
*/
private Bitmap getBitmapFromCache(Stringurl) {
// 先從mHardBitmapCache緩存中獲取
synchronized (mHardBitmapCache) {
final Bitmap bitmap =mHardBitmapCache.get(url);
if (bitmap != null) {
//若是找到的話,把元素移到linkedhashmap的最前面,從而保證在LRU算法中是最後被刪除
mHardBitmapCache.remove(url);
mHardBitmapCache.put(url,bitmap);
return bitmap;
}
}
//若是mHardBitmapCache中找不到,到mSoftBitmapCache中找
SoftReference<Bitmap>bitmapReference = mSoftBitmapCache.get(url);
if (bitmapReference != null) {
final Bitmap bitmap =bitmapReference.get();
if (bitmap != null) {
return bitmap;
} else {
mSoftBitmapCache.remove(url);
}
}
return null;
}
這是兩種作法,還有一些應用在下載的時候使用了線程池和消息隊列MQ,對於圖片下載的效率要更好一些。有興趣的同窗能夠看下。
總結