Android遠(yuǎn)程獲取圖片并本地緩存
對(duì)于客戶端——服務(wù)器端應(yīng)用,從遠(yuǎn)程獲取圖片算是經(jīng)常要用的一個(gè)功能,而圖片資源往往會(huì)消耗比較大的流量,對(duì)應(yīng)用來說,如果處理不好這個(gè)問題,那會(huì)讓用戶很崩潰,不知不覺手機(jī)流量就用完了,等用戶發(fā)現(xiàn)是你的應(yīng)用消耗掉了他手機(jī)流量的話,那么可想而知你的應(yīng)用將面臨什么樣的命運(yùn)。
另外一個(gè)問題就是加載速度,如果應(yīng)用中圖片加載速度很慢的話,那么用戶同樣會(huì)等到崩潰。
那么如何處理好圖片資源的獲取和管理呢?
- *異步下載
- *本地緩存
1、異步下載:
大家都知道,在android應(yīng)用中UI線程5秒沒響應(yīng)的話就會(huì)拋出無響應(yīng)異常,對(duì)于遠(yuǎn)程獲取大的資源來說,這種異常還是很容易就會(huì)拋出來的,那么怎么避免這種問題的產(chǎn)生。在android中提供兩種方法來做這件事情:
啟動(dòng)一個(gè)新的線程來獲取資源,完成后通過Handler機(jī)制發(fā)送消息,并在UI線程中處理消息,從而達(dá)到在異步線程中獲取圖片,然后通過Handler Message來更新UI線程的過程。
使用android中提供的AsyncTask來完成。
具體的做法這里就不介紹了,查下API就可以了,或者是google、baidu下。這里主要來說本地緩存。
2、本地緩存:
對(duì)于圖片資源來說,你不可能讓應(yīng)用每次獲取的時(shí)候都重新到遠(yuǎn)程去下載(ListView),這樣會(huì)浪費(fèi)資源,但是你又不能讓所有圖片資源都放到內(nèi)存中去(雖然這樣加載會(huì)比較快),因?yàn)閳D片資源往往會(huì)占用很大的內(nèi)存空間,容易導(dǎo)致OOM。那么如果下載下來的圖片保存到SDCard中,下次直接從SDCard上去獲取呢?這也是一種做法,我看了下,還是有不少應(yīng)用采用這種方式的。采用LRU等一些算法可以保證sdcard被占用的空間只有一小部分,這樣既保證了圖片的加載、節(jié)省了流量、又使SDCard的空間只占用了一小部分。另外一種做法是資源直接保存在內(nèi)存中,然后設(shè)置過期時(shí)間和LRU規(guī)則。
sdcard保存:
在sdcard上開辟一定的空間,需要先判斷sdcard上剩余空間是否足夠,如果足夠的話就可以開辟一些空間,比如10M
當(dāng)需要獲取圖片時(shí),就先從sdcard上的目錄中去找,如果找到的話,使用該圖片,并更新圖片最后被使用的時(shí)間。如果找不到,通過URL去download 去服務(wù)器端下載圖片,如果下載成功了,放入到sdcard上,并使用,如果失敗了,應(yīng)該有重試機(jī)制。比如3次。
下載成功后保存到sdcard上,需要先判斷10M空間是否已經(jīng)用完,如果沒有用完就保存,如果空間不足就根據(jù)LRU規(guī)則刪除一些最近沒有被用戶的資源。
關(guān)鍵代碼:
保存圖片到SD卡上:
private void saveBmpToSd(Bitmap bm, Stringurl) { if (bm == null) { Log.w(TAG, " trying to savenull bitmap"); return; } //判斷sdcard上的空間 if (FREE_SD_SPACE_NEEDED_TO_CACHE >freeSpaceOnSd()) { Log.w(TAG, "Low free space onsd, do not cache"); return; } String filename =convertUrlToFileName(url); String dir = getDirectory(filename); File file = new File(dir +"/" + filename); try { file.createNewFile(); OutputStream outStream = newFileOutputStream(file); bm.compress(Bitmap.CompressFormat.JPEG, 100, outStream); outStream.flush(); outStream.close(); Log.i(TAG, "Image saved tosd"); } catch (FileNotFoundException e) { Log.w(TAG,"FileNotFoundException"); } catch (IOException e) { Log.w(TAG,"IOException"); } }
計(jì)算sdcard上的空間:
/** * 計(jì)算sdcard上的剩余空間 * @return */ private int freeSpaceOnSd() { StatFs stat = newStatFs(Environment.getExternalStorageDirectory() .getPath()); double sdFreeMB = ((double)stat.getAvailableBlocks() * (double) stat.getBlockSize()) / MB; return (int) sdFreeMB; }
修改文件的最后修改時(shí)間 :
/** * 修改文件的最后修改時(shí)間 * @param dir * @param fileName */ private void updateFileTime(String dir,String fileName) { File file = new File(dir,fileName); long newModifiedTime =System.currentTimeMillis(); file.setLastModified(newModifiedTime); }
本地緩存優(yōu)化:
/** *計(jì)算存儲(chǔ)目錄下的文件大小,當(dāng)文件總大小大于規(guī)定的CACHE_SIZE或者sdcard剩余空間小于FREE_SD_SPACE_NEEDED_TO_CACHE的規(guī)定 * 那么刪除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(); } }
文件使用時(shí)間排序:
/** * TODO 根據(jù)文件的最后修改時(shí)間進(jìn)行排序 * */ 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; } } }
內(nèi)存保存:
在內(nèi)存中保存的話,只能保存一定的量,而不能一直往里面放,需要設(shè)置數(shù)據(jù)的過期時(shí)間、LRU等算法。這里有一個(gè)方法是把常用的數(shù)據(jù)放到一個(gè)緩存中(A),不常用的放到另外一個(gè)緩存中(B)。當(dāng)要獲取數(shù)據(jù)時(shí)先從A中去獲取,如果A中不存在那么再去B中獲取。B中的數(shù)據(jù)主要是A中LRU出來的數(shù)據(jù),這里的內(nèi)存回收主要針對(duì)B內(nèi)存,從而保持A中的數(shù)據(jù)可以有效的被命中。
先定義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) { //當(dāng)map的size大于30時(shí),把最近不常用的key放到mSoftBitmapCache中,從而保證mHardBitmapCache的效率 mSoftBitmapCache.put(eldest.getKey(), newSoftReference<Bitmap>(eldest.getValue())); return true; } else return false; } };
再定義B緩存:
/** *當(dāng)mHardBitmapCache的key大于30的時(shí)候,會(huì)根據(jù)LRU算法把最近沒有被使用的key放入到這個(gè)緩存中。 *Bitmap使用了SoftReference,當(dāng)內(nèi)存空間不足時(shí),此cache中的bitmap會(huì)被垃圾回收掉 */ private final staticConcurrentHashMap<String, SoftReference<Bitmap>> mSoftBitmapCache =new ConcurrentHashMap<String,SoftReference<Bitmap>>(HARD_CACHE_CAPACITY / 2); 從緩存中獲取數(shù)據(jù): /** * 從緩存中獲取圖片 */ 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; }
如果緩存中不存在,那么就只能去服務(wù)器端去下載:
/** * 異步下載圖片 */ class ImageDownloaderTask extendsAsyncTask<String, Void, Bitmap> { private static final int IO_BUFFER_SIZE= 4 * 1024; private String url; private finalWeakReference<ImageView> imageViewReference; public ImageDownloaderTask(ImageViewimageView) { imageViewReference = newWeakReference<ImageView>(imageView); } @Override protected BitmapdoInBackground(String... params) { final AndroidHttpClient client =AndroidHttpClient.newInstance("Android"); url = params[0]; final HttpGet getRequest = newHttpGet(url); try { HttpResponse response =client.execute(getRequest); final int statusCode =response.getStatusLine().getStatusCode(); if (statusCode !=HttpStatus.SC_OK) { Log.w(TAG, "從" +url + "中下載圖片時(shí)出錯(cuò)!,錯(cuò)誤碼:" + statusCode); return null; } final HttpEntity entity =response.getEntity(); if (entity != null) { InputStream inputStream =null; OutputStream outputStream =null; try { inputStream =entity.getContent(); finalByteArrayOutputStream dataStream = new ByteArrayOutputStream(); outputStream = newBufferedOutputStream(dataStream, IO_BUFFER_SIZE); copy(inputStream,outputStream); outputStream.flush(); final byte[] data =dataStream.toByteArray(); final Bitmap bitmap =BitmapFactory.decodeByteArray(data, 0, data.length); return bitmap; } finally { if (inputStream !=null) { inputStream.close(); } if (outputStream !=null) { outputStream.close(); } entity.consumeContent(); } } } catch (IOException e) { getRequest.abort(); Log.w(TAG, "I/O errorwhile retrieving bitmap from " + url, e); } catch (IllegalStateException e) { getRequest.abort(); Log.w(TAG, "Incorrect URL:" + url); } catch (Exception e) { getRequest.abort(); Log.w(TAG, "Error whileretrieving bitmap from " + url, e); } finally { if (client != null) { client.close(); } } return null; }
這是兩種做法,還有一些應(yīng)用在下載的時(shí)候使用了線程池和消息隊(duì)列MQ,對(duì)于圖片下載的效率要更好一些。有興趣的同學(xué)可以看下。
總結(jié): 對(duì)于遠(yuǎn)程圖片等相對(duì)比較大的資源一定要在異步線程中去獲取本地做緩存。
以上就是Android遠(yuǎn)程獲取圖片并本地緩存方法的詳細(xì)介紹,希望對(duì)大家的學(xué)習(xí)有所幫助。
相關(guān)文章
Android開發(fā)使用json實(shí)現(xiàn)服務(wù)器與客戶端數(shù)據(jù)的交互功能示例
這篇文章主要介紹了Android開發(fā)使用json實(shí)現(xiàn)服務(wù)器與客戶端數(shù)據(jù)的交互功能,結(jié)合具體實(shí)例形式分析了Android使用json格式數(shù)據(jù)在服務(wù)器與客戶端傳遞實(shí)現(xiàn)數(shù)據(jù)庫查詢功能的步驟與相關(guān)操作技巧,需要的朋友可以參考下2017-10-10Android中Market的Loading效果實(shí)現(xiàn)方法
這篇文章主要介紹了Android中Market的Loading效果實(shí)現(xiàn)方法,較為詳細(xì)的分析了Android中l(wèi)oading效果的相關(guān)布局及功能實(shí)現(xiàn)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-10-10Android個(gè)人中心的頭像上傳,圖片編碼及截取實(shí)例
本篇文章主要介紹了Android個(gè)人中心的頭像上傳,圖片編碼及截取實(shí)例,非常具有實(shí)用價(jià)值,需要的朋友可以參考下。2016-12-12Android編程簡單獲取網(wǎng)絡(luò)上的圖片
這篇文章主要介紹了Android編程簡單獲取網(wǎng)絡(luò)上的圖片,結(jié)合實(shí)例形式分析了Android獲取網(wǎng)絡(luò)圖片及加載顯示的相關(guān)操作步驟與注意事項(xiàng),需要的朋友可以參考下2016-10-10Android使用系統(tǒng)自帶的相機(jī)實(shí)現(xiàn)一鍵拍照功能
這篇文章主要介紹了Android使用系統(tǒng)自帶的相機(jī)實(shí)現(xiàn)一鍵拍照功能,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友參考下2017-01-01Android中簡單的電話管理與短信管理App編寫實(shí)例
這篇文章主要介紹了Android中簡單的電話管理與短信管理App編寫實(shí)例,包括監(jiān)聽電話的呼叫狀態(tài)以及短信群發(fā)聯(lián)系人選擇等基本功能的實(shí)現(xiàn),代碼突出要點(diǎn),需要的朋友可以參考下2016-04-04