一、緩存介紹:
(一)、Android中緩存的必要性:
智能手機(jī)的緩存管理應(yīng)用非常的普遍和需要,是提高用戶體驗(yàn)的有效手段之一。
1、沒有緩存的弊端:
流量開銷:對于客戶端——服務(wù)器端應(yīng)用,從遠(yuǎn)程獲取圖片算是經(jīng)常要用的一個功能,而圖片資源往往會消耗比較大的流量。
加載速度:如果應(yīng)用中圖片加載速度很慢的話,那么用戶體驗(yàn)會非常糟糕。
那么如何處理好圖片資源的獲取和管理呢?異步下載+本地緩存
2、緩存帶來的好處:
- 服務(wù)器的壓力大大減?。?/li>
- 客戶端的響應(yīng)速度大大變快(用戶體驗(yàn)好);
- 客戶端的數(shù)據(jù)加載出錯情況大大較少,大大提高了應(yīng)有的穩(wěn)定性(用戶體驗(yàn)好);
- 一定程度上可以支持離線瀏覽(或者說為離線瀏覽提供了技術(shù)支持)。
3、緩存管理的應(yīng)用場景: - 提供網(wǎng)絡(luò)服務(wù)的應(yīng)用;
- 數(shù)據(jù)更新不需要實(shí)時更新,即便是允許3-5分鐘的延遲也建議采用緩存機(jī)制;
- 緩存的過期時間是可以接受的(不會因?yàn)榫彺鎺淼暮锰?,?dǎo)致某些數(shù)據(jù)因?yàn)楦虏患皶r而影響產(chǎn)品的形象等)
4、大位圖導(dǎo)致內(nèi)存開銷大的原因是什么?
1.下載或加載的過程中容易導(dǎo)致阻塞;
大位圖Bitmap對象是png格式的圖片的30至100倍;
2.大位圖在加載到ImageView控件前的解碼過程;BitmapFactory.decodeFile()會有內(nèi)存消耗。(decodeByteArray())
5、緩存設(shè)計(jì)的要點(diǎn):
1.命中率;
2.合理分配占用的空間;
3.合理的緩存層級。
(二)、加載圖片的正確流程是:“內(nèi)存-文件-網(wǎng)絡(luò) 三層cache策略”
1、先從內(nèi)存緩存中獲取,取到則返回,取不到則進(jìn)行下一步;
2、從文件緩存中獲取,取到則返回并更新到內(nèi)存緩存,取不到則進(jìn)行下一步;
3、從網(wǎng)絡(luò)下載圖片,并更新到內(nèi)存緩存和文件緩存。
具體說就是:同一張圖片只要從網(wǎng)絡(luò)獲取一次,然后在本地緩存起來,之后加載同一張圖片時就從緩存中去加載。從內(nèi)存緩存讀取圖片是最快的,但是因?yàn)閮?nèi)存容量有限,所以最好再加上文件緩存。文件緩存空間也不是無限大的,容量越大讀取效率越低,因此可以設(shè)置一個限定大小比如10M,或者限定保存時間比如一天。
在鍵值對(key-value)中,圖片緩存的key是圖片url的hash值,value就是bitmap。所以,按照這個邏輯,只要一個url被下載過,其圖片就被緩存起來了。
(三)、內(nèi)存緩存分類:
在JDK1.2以前的版本中,當(dāng)一個對象不被任何變量引用,那么程序就無法再使用這個對象。也就是說,只有對象處于可觸及狀態(tài),程序才能使用它。這 就像在日常生活中,從商店購買了某樣物品后,如果有用,就一直保留它,否則就把它扔到垃圾箱,由清潔工人收走。一般說來,如果物品已經(jīng)被扔到垃圾箱,想再 把它撿回來使用就不可能了。但有時候情況并不這么簡單,你可能會遇到類似雞肋一樣的物品,食之無味,棄之可惜。這種物品現(xiàn)在已經(jīng)無用了,保留它會占空間,但是立刻扔掉它也不劃算,因?yàn)橐苍S將來還會派用場。對于這樣的可有可無的物品,一種折衷的處理辦法是:如果家里空間足夠,就先把它保留在家里,如果家里空間不夠,即使把家里所有的垃圾清除,還是無法容納那些必不可少的生活用品,那么再扔掉這些可有可無的物品。
從JDK1.2版本開始,把對象的引用分為四種級別,從而使程序能更加靈活的控制對象的生命周期。
這四種級別由高到低依次為:強(qiáng)引用、軟引用、弱引用和虛引用。
1、強(qiáng)引用
:(在Android中LruCache就是強(qiáng)引用緩存
)
平時我們編程的時候例如:Object object=new Object();那object就是一個強(qiáng)引用了。如果一個對象具有強(qiáng)引用,那就類似于必不可少的生活用品,垃圾回收器絕不會回收它
。當(dāng)內(nèi)存空間不足,Java虛擬機(jī)寧愿拋出OOM
異常,使程序異常終止,也不會回收具有強(qiáng)引用的對象來解決內(nèi)存不足問題。
2、軟引用
(SoftReference):
軟引用類似于可有可無的生活用品。如果內(nèi)存空間足夠,垃圾回收器就不會回收它,如果內(nèi)存空間不足了,就會回收這些對象的內(nèi)存
。只要垃圾回收器沒有回收它,該對象就可以被程序使用。軟引用可用來實(shí)現(xiàn)內(nèi)存敏感的高速緩存。 軟引用可以和一個引用隊(duì)列(ReferenceQueue)聯(lián)合使用,如果軟引用所引用的對象被垃圾回收,Java虛擬機(jī)就會把這個軟引用加入到與之關(guān)聯(lián)的引用隊(duì)列中。
使用軟引用能防止內(nèi)存泄露,增強(qiáng)程序的健壯性。
3、弱引用
(WeakReference):
弱引用與軟引用的區(qū)別在于:只具有弱引用的對象擁有更短暫的生命周期。在垃圾回收器線程掃描它所管轄的內(nèi)存區(qū)域的過程中,一旦發(fā)現(xiàn)了只具有弱引用的對象,不管當(dāng)前內(nèi)存空間足夠與否
,都會回收它的內(nèi)存。不過,由于垃圾回收器是一個優(yōu)先級很低的線程, 因此不一定會很快發(fā)現(xiàn)那些只具有弱引用的對象。 弱引用可以和一個引用隊(duì)列(ReferenceQueue)聯(lián)合使用,如果弱引用所引用的對象被垃圾回收,Java虛擬機(jī)就會把這個弱引用加入到與之關(guān)聯(lián)的引用隊(duì)列中。
4、虛引用
(PhantomReference)
"虛引用"顧名思義,就是形同虛設(shè)
,與其他幾種引用都不同,虛引用并不會決定對象的生命周期。如果一個對象僅持有虛引用,那么它就和沒有任何引用一樣,在任何時候都可能被垃圾回收
。 虛引用主要用來跟蹤對象被垃圾回收的活動
虛引用與軟引用和弱引用的一個區(qū)別在于:虛引用必須和引用隊(duì)列(ReferenceQueue)聯(lián)合使用。當(dāng)垃圾回收器準(zhǔn)備回收一個對象時,如果發(fā)現(xiàn)它還有虛引用,就會在回收對象的內(nèi)存之前,把這個虛引用加入到與之關(guān)聯(lián)的引用隊(duì)列中。程序可以通過判斷引用隊(duì)列中是否已經(jīng)加入了虛引用,來了解被引用的對象是否將要被垃圾回收。程序如果發(fā)現(xiàn)某個虛引用已經(jīng)被加入到引用隊(duì)列,那么就可以在所引用的對象的內(nèi)存被回收之前采取必要的行動。
【相關(guān)應(yīng)用:】
在java.lang.ref包中提供了三個類:SoftReference
類、WeakReference
類和PhantomReference
類,它們分別代表軟引用、弱引用和虛引用。ReferenceQueue類表示引用隊(duì)列,它可以和這三種引用類聯(lián)合使用,以便跟蹤Java虛擬機(jī)回收所引用的對 象的活動。
(四)、內(nèi)存保存:
在內(nèi)存中保存的話,只能保存一定的量,而不能一直往里面放,需要設(shè)置數(shù)據(jù)的過期時間、LRU等算法。這里有一個方法是把常用的數(shù)據(jù)放到一個緩存中(A),不常用的放到另外一個緩存中(B)。當(dāng)要獲取數(shù)據(jù)時先從A中去獲取,如果A中不存在那么再去B中獲取。B中的數(shù)據(jù)主要是A中LRU出來的數(shù)據(jù),這里的內(nèi)存回收主要針對B內(nèi)存,從而保持A中的數(shù)據(jù)可以有效的被命中。
(五)、緩存的案例代碼:
**public****class** MainActivity **extends** Activity {**private****final****static** String *TAG* = "MainActivity";**private** ImageView imageView_main;**private** ProgressDialog pDialog = **null**;**private** String urlString = "http://c.hiphotos.baidu.com/image/pic/item/5366d0160924ab18dd54473737fae6cd7b890b6b.jpg";// private String urlString = "http://www.baidu.com/img/bdlogo.gif";**private** LruCache<String, Bitmap> lruCache = **null**;**private** HashMap<String, SoftReference<Bitmap>> softMap = **new** HashMap<String, SoftReference<Bitmap>>();**private** Handler handler = **new**Handler() {**public****void** handleMessage(Message msg) {**switch** (msg.what) {**case** 0:pDialog.show();**break**;**case** 1:Bitmap bm = (Bitmap) msg.obj;**if** (bm != **null**) {imageView_main.setImageBitmap(bm);}pDialog.dismiss();**break**;**default**:**break**;}}};@Override**protected****void** onCreate(Bundle savedInstanceState) {**super**.onCreate(savedInstanceState);setContentView(R.layout.*activity_main*);imageView_main = (ImageView) findViewById(R.id.*imageView_main*);pDialog = **new** ProgressDialog(**this**);pDialog.setIcon(R.drawable.*ic_launcher*);pDialog.setTitle("提示:");pDialog.setMessage("數(shù)據(jù)加載中。。。");// int memClass = ((ActivityManager)// getSystemService(Context.ACTIVITY_SERVICE))// .getMemoryClass();**int** memoryCount = (**int**) Runtime.*getRuntime*().maxMemory();// 獲取剩余內(nèi)存的8分之一作為緩存**int** cacheSize = memoryCount / 8;Log.*i*(*TAG*, "==" + cacheSize);lruCache = **new** MyLruCache(cacheSize);// 這個初始化值是如何定義的?}**class** MyLruCache **extends** LruCache<String, Bitmap> {**public** MyLruCache(**int** maxSize) {**super**(maxSize);}@Override**protected****int** sizeOf(String key, Bitmap value) {// return value.getHeight() * value.getWidth() * 4;// Bitmap圖片的一個像素是4個字節(jié)Log.*i*(*TAG*, "==" + value.getByteCount());**return** value.getByteCount();
}reference@Override**protected ****void** entryRemoved(**boolean** evicted, String key,Bitmap oldValue, Bitmap newValue) {**if** (evicted) {SoftReference<Bitmap> softReference = **new** SoftReference<Bitmap>(oldValue);softMap.put(key, softReference);}}}**public****void** clickButton(View view) {**switch** (view.getId()) {**case** R.id.*button_main_submit*:Bitmap bm = getBitmapFromMemoryCache(urlString);**if** (bm != **null**) {imageView_main.setImageBitmap(bm);Log.*i*(*TAG*, "==從緩存中獲取到的圖片");} **else** {**new** Thread(**new** Runnable() {@Override**public****void** run() {handler.sendEmptyMessage(0);HttpClient httpClient = **new** DefaultHttpClient();HttpGet httpGet = **new** HttpGet(urlString);**try** {HttpResponse response = httpClient.execute(httpGet);**if** (response.getStatusLine().getStatusCode() == 200) {**byte**[] data = EntityUtils.*toByteArray*(response.getEntity());Log.*i*(*TAG*, "==文件尺寸:" + data.length);Bitmap bm = BitmapFactory.*decodeByteArray*(data,0, data.length);// 放入強(qiáng)緩存lruCache.put(urlString, bm);Log.*i*(*TAG*, "==放入強(qiáng)緩存ok");Message msg = Message.*obtain*();msg.obj = bm;msg.what = 1;handler.sendMessage(msg);}} **catch** (IOException e) {e.printStackTrace();}}}).start();}**break**;**default**:**break**;}}**public** Bitmap getBitmapFromMemoryCache(String key) {// 1.先從強(qiáng)引用中獲取Bitmap bitmap = **null**;bitmap = lruCache.get(key);**if** (bitmap != **null**) {Log.*i*(*TAG*, "==從強(qiáng)引用中找到");**return** bitmap;} **else** {// 2.如果強(qiáng)引用中沒有找到的話 如果軟引用中存在就將它移到強(qiáng)引用中 然后軟引用移除SoftReference<Bitmap> softReference = softMap.get(key);**if** (softReference != **null**) {bitmap = softReference.get();Log.*i*(*TAG*, "==從軟引用中找到");**if** (bitmap != **null**) {// 添加到強(qiáng)引用中l(wèi)ruCache.put(key, bitmap);Log.*i*(*TAG*, "==添加到強(qiáng)引用中");// 從軟引用集合中移除softMap.remove(key);Log.*i*(*TAG*, "==從軟引用中移除");**return** bitmap;} **else** {softMap.remove(key);}}}**return****null**;}@Override**public****boolean** onCreateOptionsMenu(Menu menu) {getMenuInflater().inflate(R.menu.*next*, menu);**return****true**;}}
二、封裝異步任務(wù)類:
(一)、
AsynTaskHelper的核心代碼:
**public****class** AsynTaskHelper {**private****static****final** String *TAG* = "AsynTaskHelper";**public****void** downloadData(String url, OnDataDownloadListener downloadListener) {**new** MyTask(downloadListener).execute(url);}**private****class** MyTask **extends** AsyncTask<String, Void, **byte**[]> {**private** OnDataDownloadListener downloadListener;**public** MyTask(OnDataDownloadListener downloadListener) {**this**.downloadListener = downloadListener;}@Override**protected****byte**[] doInBackground(String... params) {BufferedInputStream bis = **null**;ByteArrayOutputStream baos = **new** ByteArrayOutputStream();**try** {URL url = **new** URL(params[0]);HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();httpConn.setDoInput(**true**);httpConn.setRequestMethod("GET");httpConn.connect();**if** (httpConn.getResponseCode() == 200) {bis = **new** BufferedInputStream(httpConn.getInputStream());**byte**[] buffer = **new****byte**[1024 * 8];**int** c = 0;**while** ((c = bis.read(buffer)) != -1) {baos.write(buffer, 0, c);baos.flush();}**return** baos.toByteArray();}} **catch** (Exception e) {e.printStackTrace();}**return****null**;}@Override**protected****void** onPostExecute(**byte**[] result) {// 通過回調(diào)接口來傳遞數(shù)據(jù)downloadListener.onDataDownload(result);**super**.onPostExecute(result);}}**public****interface** OnDataDownloadListener {**void** onDataDownload(**byte**[] result);}}
三、帶有緩存的異步加載圖片類
:
(一)、ImageDownloaderHelper
的核心代碼:
**public****class** ImageDownloadHelper {**private****static****final** String *TAG* = "ImageDownloaderHelper";**private** HashMap<String, MyAsyncTask> map = **new** HashMap<String, MyAsyncTask>();**private** Map<String, SoftReference<Bitmap>> softCaches = **new** LinkedHashMap<String, SoftReference<Bitmap>>();**private** LruCache<String, Bitmap> lruCache = **null**;**public** ImageDownloadHelper() {**int** memoryAmount = (**int**) Runtime.*getRuntime*().maxMemory();// 獲取剩余內(nèi)存的8分之一作為緩存**int** cacheSize = memoryAmount / 8;**if** (lruCache == **null**) {lruCache = **new** MyLruCache(cacheSize);}Log.*i*(*TAG*, "==LruCache尺寸:" + cacheSize);}/** * * **@param** context * **@param** url * 該mImageView對應(yīng)的url * **@param** mImageView * **@param** path * 文件存儲路徑 * **@param** downloadListener * OnImageDownload回調(diào)接口,在onPostExecute()中被調(diào)用 */**public****void** imageDownload(Context context, String url,ImageView mImageView, String path,OnImageDownloadListener downloadListener) {Bitmap bitmap = **null**;// 先從強(qiáng)引用中拿數(shù)據(jù)**if** (lruCache != **null**) {bitmap = lruCache.get(url);}**if** (bitmap != **null** && url.equals(mImageView.getTag())) {Log.*i*(*TAG*, "==從強(qiáng)引用中找到數(shù)據(jù)");mImageView.setImageBitmap(bitmap);} **else** {SoftReference<Bitmap> softReference = softCaches.get(url);**if** (softReference != **null**) {bitmap = softReference.get();}// 從軟引用中拿數(shù)據(jù)**if** (bitmap != **null** && url.equals(mImageView.getTag())) {Log.*i*(*TAG*, "==從軟引用中找到數(shù)據(jù)");// 添加到強(qiáng)引用中l(wèi)ruCache.put(url, bitmap);Log.*i*(*TAG*, "==添加到強(qiáng)引用中");// 從軟引用集合中移除softCaches.remove(url);mImageView.setImageBitmap(bitmap);} **else** {// 從文件緩存中拿數(shù)據(jù)String imageName = "";**if** (url != **null**) {imageName = ImageDownloaderUtil.*getInstance*().getImageName(url);}bitmap = getBitmapFromFile(context, imageName, path);**if** (bitmap != **null** && url.equals(mImageView.getTag())) {Log.*i*(*TAG*, "==從文件緩存中找到數(shù)據(jù)");// 放入強(qiáng)緩存lruCache.put(url, bitmap);mImageView.setImageBitmap(bitmap);} **else** {// 從網(wǎng)絡(luò)中拿數(shù)據(jù)**if** (url != **null** && needCreateNewTask(mImageView)) {MyAsyncTask task = **new** MyAsyncTask(context, url,mImageView, path, downloadListener);Log.*i*(*TAG*, "==從網(wǎng)絡(luò)中拿數(shù)據(jù)");**if** (mImageView != **null**) {task.execute();// 將對應(yīng)的url對應(yīng)的任務(wù)存起來map.put(url, task);}}}}}}/** * 判斷是否需要重新創(chuàng)建線程下載圖片,如果需要,返回值為true。 * * **@param** url * **@param** mImageView * **@return** */**private****boolean** needCreateNewTask(ImageView mImageView) {**boolean** b = **true**;**if** (mImageView != **null**) {String curr_task_url = (String) mImageView.getTag();**if** (isTasksContains(curr_task_url)) {b = **false**;}}**return** b;}/** * 檢查該url(最終反映的是當(dāng)前的ImageView的tag,tag會根據(jù)position的不同而不同)對應(yīng)的task是否存在 * * **@param** url * **@return** */**private****boolean** isTasksContains(String url) {**boolean** b = **false**;**if** (map != **null** && map.get(url) != **null**) {b = **true**;}**return** b;}/** * 刪除map中該url的信息,這一步很重要,不然MyAsyncTask的引用會“一直”存在于map中 * * **@param** url */**private****void** removeTaskFromMap(String url) {**if** (url != **null** && map != **null** && map.get(url) != **null**) {map.remove(url);Log.*i*(*TAG*, "當(dāng)前map的大小==" + map.size());}}/** * 從文件中拿圖片 * * **@param** mActivity * **@param** imageName * 圖片名字 * **@param** path * 圖片路徑 * **@return** */**private** Bitmap getBitmapFromFile(Context context, String imageName,String path) {Bitmap bitmap = **null**;**if** (imageName != **null**) {File file = **null**;String real_path = "";**try** {**if** (ImageDownloaderUtil.*getInstance*().hasSDCard()) {real_path = ImageDownloaderUtil.*getInstance*().getExtPath()+ (path != **null** && path.startsWith("/") ? path: "/" + path);} **else** {real_path = ImageDownloaderUtil.*getInstance*().getPackagePath(context)+ (path != **null** && path.startsWith("/") ? path: "/" + path);}file = **new** File(real_path, imageName);**if** (file.exists())bitmap = BitmapFactory.*decodeStream*(**new** FileInputStream(file));} **catch** (Exception e) {e.printStackTrace();bitmap = **null**;}}**return** bitmap;}/** * 將下載好的圖片存放到文件中 * * **@param** path * 圖片路徑 * **@param** mActivity * **@param** imageName * 圖片名字 * **@param** bitmap * 圖片 * **@return** */**private****boolean** setBitmapToFile(String path, Context mActivity,String imageName, Bitmap bitmap) {File file = **null**;String real_path = "";**try** {**if** (ImageDownloaderUtil.*getInstance*().hasSDCard()) {real_path = ImageDownloaderUtil.*getInstance*().getExtPath()+ (path != **null** && path.startsWith("/") ? path : "/"+ path);} **else** {real_path = ImageDownloaderUtil.*getInstance*().getPackagePath(mActivity)+ (path != **null** && path.startsWith("/") ? path : "/"+ path);}file = **new** File(real_path, imageName);**if** (!file.exists()) {File file2 = **new** File(real_path + "/");file2.mkdirs();}file.createNewFile();FileOutputStream fos = **null**;**if** (ImageDownloaderUtil.*getInstance*().hasSDCard()) {fos = **new** FileOutputStream(file);} **else** {fos = mActivity.openFileOutput(imageName, Context.*MODE_PRIVATE*);}**if** (imageName != **null**&& (imageName.contains(".png") || imageName.contains(".PNG"))) {bitmap.compress(Bitmap.CompressFormat.*PNG*, 90, fos);} **else** {bitmap.compress(Bitmap.CompressFormat.*JPEG*, 90, fos);}fos.flush();**if** (fos != **null**) {fos.close();}**return****true**;} **catch** (Exception e) {e.printStackTrace();**return****false**;}}/** * 輔助方法,一般不調(diào)用 * * **@param** path * **@param** mActivity * **@param** imageName */**private****void** removeBitmapFromFile(String path, Context mActivity,String imageName) {File file = **null**;String real_path = "";**try** {**if** (ImageDownloaderUtil.*getInstance*().hasSDCard()) {real_path = ImageDownloaderUtil.*getInstance*().getExtPath()+ (path != **null** && path.startsWith("/") ? path : "/"+ path);} **else** {real_path = ImageDownloaderUtil.*getInstance*().getPackagePath(mActivity)+ (path != **null** && path.startsWith("/") ? path : "/"+ path);}file = **new** File(real_path, imageName);**if** (file != **null**)file.delete();} **catch** (Exception e) {e.printStackTrace();}}/** * 異步下載圖片的方法 * * **@author** * */**private****class** MyAsyncTask **extends** AsyncTask<String, Void, Bitmap> {**private** Context context;**private** ImageView mImageView;**private** String url;**private** OnImageDownloadListener downloadListener;**private** String path;**public** MyAsyncTask(Context context, String url, ImageView mImageView,String path, OnImageDownloadListener downloadListener) {**this**.context = context;**this**.url = url;**this**.mImageView = mImageView;**this**.path = path;**this**.downloadListener = downloadListener;}@Override**protected** Bitmap doInBackground(String... params) {Bitmap bm = **null**;**if** (url != **null**) {**try** {Log.*i*(*TAG*, "==訪問網(wǎng)絡(luò)加載圖片");URL urlObj = **new** URL(url);HttpURLConnection httpConn = (HttpURLConnection) urlObj.openConnection();httpConn.setDoInput(**true**);httpConn.setRequestMethod("GET");httpConn.connect();**if** (httpConn.getResponseCode() == 200) {InputStream is = httpConn.getInputStream();bm = BitmapFactory.*decodeStream*(is);}String imageName = ImageDownloaderUtil.*getInstance*().getImageName(url);**if** (!setBitmapToFile(path, context, imageName, bm)) {removeBitmapFromFile(path, context, imageName);}// 放入強(qiáng)緩存lruCache.put(url, bm);Log.*i*(*TAG*, "==放入強(qiáng)緩存ok");} **catch** (Exception e) {e.printStackTrace();}}**return** bm;}@Override**protected****void** onPostExecute(Bitmap result) {// 回調(diào)設(shè)置圖片**if** (downloadListener != **null**) {downloadListener.onImageDownload(result, url);// 該url對應(yīng)的task已經(jīng)下載完成,從map中將其刪除removeTaskFromMap(url);}**super**.onPostExecute(result);}}**public****interface** OnImageDownloadListener {**void** onImageDownload(Bitmap bitmap, String imgUrl);}// 定義強(qiáng)引用緩存**class** MyLruCache **extends** LruCache<String, Bitmap> {**public** MyLruCache(**int** maxSize) {**super**(maxSize);}@Override**protected****int** sizeOf(String key, Bitmap value) {// return value.getHeight() * value.getWidth() * 4;// Bitmap圖片的一個像素是4個字節(jié)**return** value.getByteCount();}@Override**protected****void** entryRemoved(**boolean** evicted, String key,Bitmap oldValue, Bitmap newValue) {**if** (evicted) {SoftReference<Bitmap> softReference = **new** SoftReference<Bitmap>(oldValue);softCaches.put(key, softReference);}}}**static****class** ImageDownloaderUtil {**private****static** ImageDownloaderUtil *util*;**private** ImageDownloaderUtil() {}**public****static** ImageDownloaderUtil getInstance() {**if** (*util* == **null**) {*util* = **new** ImageDownloaderUtil();}**return***util*;}/** * 判斷是否有sdcard * * **@return** */**public****boolean** hasSDCard() {**boolean** b = **false**;**if** (Environment.*MEDIA_MOUNTED*.equals(Environment.*getExternalStorageState*())) {b = **true**;}**return** b;}/** * 得到sdcard路徑 * * **@return** */**public** String getExtPath() {String path = "";**if** (hasSDCard()) {path = Environment.*getExternalStorageDirectory*().getPath();}**return** path;}/** * 得到包目錄 * * **@param** mActivity * **@return** */**public** String getPackagePath(Context mActivity) {**return** mActivity.getFilesDir().toString();}/** * 根據(jù)url得到圖片名 * * **@param** url * **@return** */**public** String getImageName(String url) {String imageName = "";**if** (url != **null**) {imageName = url.substring(url.lastIndexOf("/") + 1);}**return** imageName;}}}
(二)、應(yīng)用舉例:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.item_listview_main, null);
viewHolder.CoverStoryImage = (ImageView) convertView.findViewById(R.id.CoverStoryImage);
viewHolder.CoverStoryName = (TextView) convertView.findViewById(R.id.CoverStoryName);
viewHolder.IssueDate = (TextView) convertView.findViewById(R.id.IssueDate);
viewHolder.Issue = (TextView) convertView.findViewById(R.id.Issue);
viewHolder.IssueYear = (TextView) convertView.findViewById(R.id.IssueYear);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.CoverStoryName.setText(dataList.get(position).get("CoverStoryName"));
viewHolder.IssueDate.setText(dataList.get(position).get("IssueDate"));
viewHolder.Issue.setText(dataList.get(position).get("Issue"));
viewHolder.IssueYear.setText(dataList.get(position).get("IssueYear"));
viewHolder.CoverStoryImage.setImageResource(R.drawable.defaultcovers);
// 開始加載圖片
final
String urlString = dataList.get(position).get("CoverStoryImage");
viewHolder.CoverStoryImage.setTag
(urlString);
Log.i(TAG, "settag:" + urlString);
// 方法一:增加了緩存的異步加載圖片
if (mDownloader == null) {
mDownloader = new ImageDownloader();
}
if (mDownloader != null) {
// 異步下載圖片
mDownloader.imageDownload(urlString,
viewHolder.CoverStoryImage, "/img_temp", context,new ImageDownloader.OnImageDownload() {
@Override
public void onDownloadSuccess(Bitmap bitmap,String imgUrl, ImageView imageView) {
ImageView image_item = (ImageView) imageView.findViewWithTag
(imgUrl);
if (image_item != null
) {
image_item.setImageBitmap(bitmap);
image_item.setTag(null);
Log.i(TAG, "findViewWithTag:" + imgUrl);
} else {
Log.i(TAG, "imageView is null
:" + imgUrl); //???為什么會有為null的時候呢
?
}
}
});
}
return convertView;
}
class ViewHolder {
private ImageView CoverStoryImage;
private TextView CoverStoryName;
private TextView IssueDate;
private TextView Issue;
private TextView IssueYear;
}