自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Android Bitmap緩存池使用詳解

移動(dòng)開發(fā) Android
本文介紹了如何使用緩存來提高UI的載入輸入和滑動(dòng)的流暢性。使用內(nèi)存緩存、使用磁盤緩存、處理配置改變事件等方法將會(huì)有效的解決這個(gè)問題。

本文介紹了如何使用緩存來提高UI的載入輸入和滑動(dòng)的流暢性。使用內(nèi)存緩存、使用磁盤緩存、處理配置改變事件等方法將會(huì)有效的解決這個(gè)問題。

在您的UI中顯示單個(gè)圖片是非常簡(jiǎn)單的,如果您需要一次顯示很多圖片就有點(diǎn)復(fù)雜了。在很多情況下(例如使用 ListView, GridView 或者 ViewPager控件),顯示在屏幕上的圖片以及即將顯示在屏幕上的圖片數(shù)量是非常大的(例如在圖庫中瀏覽大量圖片)。

在這些控件中,當(dāng)一個(gè)子控件不顯示的時(shí)候,系統(tǒng)會(huì)重用該控件來循環(huán)顯示 以便減少對(duì)內(nèi)存的消耗。同時(shí)垃圾回收機(jī)制還會(huì)釋放那些已經(jīng)載入內(nèi)存中的Bitmap資源(假設(shè)您沒有強(qiáng)引用這些Bitmap)。一般來說這樣都是不錯(cuò)的,但是在用戶來回滑動(dòng)屏幕的時(shí)候,為了保證UI的流暢性和載入圖片的效率,您需要避免重復(fù)的處理這些需要顯示的圖片。 使用內(nèi)存緩存和磁盤緩存可以解決這個(gè)問題,使用緩存可以讓控件快速的加載已經(jīng)處理過的圖片。

本文介紹如何使用緩存來提高UI的載入輸入和滑動(dòng)的流暢性。

使用內(nèi)存緩存

內(nèi)存緩存提高了訪問圖片的速度,但是要占用不少內(nèi)存。 LruCache類(在API 4之前可以使用Support Library 中的類 )特別適合緩存Bitmap, 把最近使用到的Bitmap對(duì)象用強(qiáng)引用保存起來(保存到LinkedHashMap中),當(dāng)緩存數(shù)量達(dá)到預(yù)定的值的時(shí)候,把不經(jīng)常使用的對(duì)象刪除。

注意: 過去,實(shí)現(xiàn)內(nèi)存緩存的常用做法是使用SoftReference 或者WeakReference bitmap 緩存,但是不推薦使用這種方式。從Android 2.3 (API Level 9) 開始,垃圾回收開始強(qiáng)制的回收掉 soft/weak 引用 從而導(dǎo)致這些緩存沒有任何效率的提升。

另外,在 Android 3.0 (API Level 11)之前,這些緩存的Bitmap數(shù)據(jù)保存在底層內(nèi)存(native memory)中,并且達(dá)到預(yù)定條件后也不會(huì)釋放這些對(duì)象,從而可能導(dǎo)致程序超過內(nèi)存限制并崩潰。

在使用 LruCache 的時(shí)候,需要考慮如下一些因素來選擇一個(gè)合適的緩存數(shù)量參數(shù):

  • 程序中還有多少內(nèi)存可用
  • 同時(shí)在屏幕上顯示多少圖片?要先緩存多少圖片用來顯示到即將看到的屏幕上?
  • 設(shè)備的屏幕尺寸和屏幕密度是多少?超高的屏幕密度(xhdpi 例如 Galaxy Nexus)
  • 設(shè)備顯示同樣的圖片要比低屏幕密度(hdpi 例如 Nexus S)設(shè)備需要更多的內(nèi)存。
  • 圖片的尺寸和格式?jīng)Q定了每個(gè)圖片需要占用多少內(nèi)存
  • 圖片訪問的頻率如何?一些圖片的訪問頻率要比其他圖片高很多?如果是這樣的話,您可能需要把這些經(jīng)常訪問的圖片放到內(nèi)存中。
  • 在質(zhì)量和數(shù)量上如何平衡?有些情況下保存大量的低質(zhì)量的圖片是非常有用的,當(dāng)需要的情況下使用后臺(tái)線程來加入一個(gè)高質(zhì)量版本的圖片。

這里沒有***配方可以適合所有的程序,您需要分析您的使用情況并在指定自己的緩存策略。使用太小的緩存并不能起到應(yīng)有的效果,而使用太大的緩存會(huì)消耗更多

的內(nèi)存從而有可能導(dǎo)致 java.lang.OutOfMemory 異常或者留下很少的內(nèi)存供您的程序其他功能使用。

下面是一個(gè)使用 LruCache 緩存的示例:

  1. private LruCache<string, bitmap=""> mMemoryCache;  
  2.  
  3. @Override  
  4. protected void onCreate(Bundle savedInstanceState) {  
  5.     ...  
  6.     // Get memory class of this device, exceeding this amount will throw an  
  7.     // OutOfMemory exception.  
  8.     final int memClass = ((ActivityManager) context.getSystemService(  
  9.             Context.ACTIVITY_SERVICE)).getMemoryClass();  
  10.  
  11.     // Use 1/8th of the available memory for this memory cache.  
  12.     final int cacheSize = 1024 * 1024 * memClass / 8;  
  13.  
  14.     mMemoryCache = new LruCache<string, bitmap="">(cacheSize) {  
  15.         @Override  
  16.         protected int sizeOf(String key, Bitmap bitmap) {  
  17.             // The cache size will be measured in bytes rather than number of items.  
  18.             return bitmap.getByteCount();  
  19.         }  
  20.     };  
  21.     ...  
  22. }                                                                
  23. public void addBitmapToMemoryCache(String key, Bitmap bitmap) {  
  24.     if (getBitmapFromMemCache(key) == null) {  
  25.         mMemoryCache.put(key, bitmap);  
  26.     }  
  27. }                                                                
  28. public Bitmap getBitmapFromMemCache(String key) {  
  29.     return mMemoryCache.get(key);  
  30.  

注意: 在這個(gè)示例中,該程序的1/8內(nèi)存都用來做緩存用了。在一個(gè)normal/hdpi設(shè)備中,這至少有4MB(32/8)內(nèi)存。

在一個(gè)分辨率為 800×480的設(shè)備中,滿屏的GridView全部填充上圖片將會(huì)使用差不多1.5MB(800*480*4 bytes)的內(nèi)存,所以這樣差不多在內(nèi)存中緩存了2.5頁的圖片。

當(dāng)在 ImageView 中顯示圖片的時(shí)候,先檢查L(zhǎng)ruCache 中是否存在。如果存在就使用緩存后的圖片,如果不存在就啟動(dòng)后臺(tái)線程去載入圖片并緩存:

  1. public void loadBitmap(int resId, ImageView imageView) {  
  2.     final String imageKey = String.valueOf(resId);  
  3.     final Bitmap bitmap = getBitmapFromMemCache(imageKey);  
  4.     if (bitmap != null) {  
  5.         mImageView.setImageBitmap(bitmap);  
  6.     } else {  
  7.         mImageView.setImageResource(R.drawable.image_placeholder);  
  8.         BitmapWorkerTask task = new BitmapWorkerTask(mImageView);  
  9.         task.execute(resId);  
  10.     }  
  11.  

BitmapWorkerTask 需要把新的圖片添加到緩存中:

  1. class BitmapWorkerTask extends AsyncTask<integer, void,="" bitmap=""> {  
  2.     ...  
  3.     // Decode image in background.  
  4.     @Override  
  5.     protected Bitmap doInBackground(Integer... params) {  
  6.         final Bitmap bitmap = decodeSampledBitmapFromResource(  
  7.                 getResources(), params[0], 100, 100));  
  8.         addBitmapToMemoryCache(String.valueOf(params[0]), bitmap);  
  9.         return bitmap;  
  10.     }  
  11.     ...  
  12.  

下頁將為您介紹其它兩種方法使用磁盤緩存和處理配置改變事件

使用磁盤緩存

在訪問最近使用過的圖片中,內(nèi)存緩存速度很快,但是您無法確定圖片是否在緩存中存在。像GridView 這種控件可能具有很多圖片需要顯示,很快圖片數(shù)據(jù)就填滿了緩存容量。

同時(shí)您的程序還可能被其他任務(wù)打斷,比如打進(jìn)的電話 — 當(dāng)您的程序位于后臺(tái)的時(shí)候,系統(tǒng)可能會(huì)清楚到這些圖片緩存。一旦用戶恢復(fù)使用您的程序,您還需要重新處理這些圖片。

在這種情況下,可以使用磁盤緩存來保存這些已經(jīng)處理過的圖片,當(dāng)這些圖片在內(nèi)存緩存中不可用的時(shí)候,可以從磁盤緩存中加載從而省略了圖片處理過程。

當(dāng)然, 從磁盤載入圖片要比從內(nèi)存讀取慢很多,并且應(yīng)該在非UI線程中載入磁盤圖片。

注意: 如果緩存的圖片經(jīng)常被使用的話,可以考慮使用ContentProvider ,例如在圖庫程序中就是這樣干滴。

在示例代碼中有個(gè)簡(jiǎn)單的 DiskLruCache 實(shí)現(xiàn)。然后,在Android 4.0中包含了一個(gè)更加可靠和推薦使用的DiskLruCache(libcore/luni/src/main/java/libcore/io/DiskLruCache.java)。您可以很容易的把這個(gè)實(shí)現(xiàn)移植到4.0之前的版本中使用(來 href=”http://www.google.com/search?q=disklrucache”>Google一下 看看其他人是否已經(jīng)這樣干了!)。

這里是一個(gè)更新版本的 DiskLruCache :

  1. private DiskLruCache mDiskCache;  
  2. private static final int DISK_CACHE_SIZE = 1024 * 1024 * 10; // 10MB  
  3. private static final String DISK_CACHE_SUBDIR = "thumbnails";  
  4.  
  5. @Override  
  6. protected void onCreate(Bundle savedInstanceState) {  
  7.     ...  
  8.     // Initialize memory cache  
  9.     ...  
  10.     File cacheDir = getCacheDir(this, DISK_CACHE_SUBDIR);  
  11.     mDiskCache = DiskLruCache.openCache(this, cacheDir, DISK_CACHE_SIZE);  
  12.     ...  
  13. }                                 
  14. class BitmapWorkerTask extends AsyncTask<integer, void,="" bitmap=""> {  
  15.     ...  
  16.     // Decode image in background.  
  17.     @Override  
  18.     protected Bitmap doInBackground(Integer... params) {  
  19.         final String imageKey = String.valueOf(params[0]);  
  20.  
  21.         // Check disk cache in background thread  
  22.         Bitmap bitmap = getBitmapFromDiskCache(imageKey);  
  23.  
  24.         if (bitmap == null) { // Not found in disk cache  
  25.             // Process as normal  
  26.             final Bitmap bitmap = decodeSampledBitmapFromResource(  
  27.                     getResources(), params[0], 100, 100));  
  28.         }                                
  29.         // Add final bitmap to caches  
  30.         addBitmapToCache(String.valueOf(imageKey, bitmap);  
  31.  
  32.         return bitmap;  
  33.     }  
  34.     ...  
  35. }                                 
  36. public void addBitmapToCache(String key, Bitmap bitmap) {  
  37.     // Add to memory cache as before  
  38.     if (getBitmapFromMemCache(key) == null) {  
  39.         mMemoryCache.put(key, bitmap);  
  40.     }                                 
  41.     // Also add to disk cache  
  42.     if (!mDiskCache.containsKey(key)) {  
  43.         mDiskCache.put(key, bitmap);  
  44.     }  
  45. }                                 
  46. public Bitmap getBitmapFromDiskCache(String key) {  
  47.     return mDiskCache.get(key);  
  48. }                                 
  49. // Creates a unique subdirectory of the designated app cache directory. Tries to use external  
  50. // but if not mounted, falls back on internal storage.  
  51. public static File getCacheDir(Context context, String uniqueName) {  
  52.     // Check if media is mounted or storage is built-in, if so, try and use external cache dir  
  53.     // otherwise use internal cache dir  
  54.     final String cachePath = Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED  
  55.             || !Environment.isExternalStorageRemovable() ?  
  56.                     context.getExternalCacheDir().getPath() : context.getCacheDir().getPath();  
  57.     return new File(cachePath + File.separator + uniqueName);  
  58.  

在UI線程中檢測(cè)內(nèi)存緩存,在后臺(tái)線程中檢測(cè)磁盤緩存。磁盤操作從來不應(yīng)該在UI線程中實(shí)現(xiàn)。當(dāng)圖片處理完畢后,最終的結(jié)果會(huì)同時(shí)添加到內(nèi)存緩存和磁盤緩存中以便將來使用。

處理配置改變事件

運(yùn)行時(shí)的配置變更 — 例如 屏幕方向改變 — 導(dǎo)致Android摧毀正在運(yùn)行的Activity,然后使用新的配置從新啟動(dòng)該Activity (詳情,參考這里 Handling Runtime Changes)。

您需要注意避免在配置改變的時(shí)候?qū)е轮匦绿幚硭械膱D片,從而提高用戶體驗(yàn)。

幸運(yùn)的是,您在 使用內(nèi)存緩存 部分已經(jīng)有一個(gè)很好的圖片緩存了。該緩存可以通過Fragment (Fragment會(huì)通過setRetainInstance(true)函數(shù)保存起來)來傳遞給新的Activity

當(dāng)Activity重新啟動(dòng) 后,F(xiàn)ragment 被重新附加到Activity中,您可以通過該Fragment來獲取緩存對(duì)象。

下面是一個(gè)在 Fragment中保存緩存的示例:

  1. private LruCache<string, bitmap=""> mMemoryCache;                   
  2. @Override  
  3. protected void onCreate(Bundle savedInstanceState) {  
  4.     ...  
  5.     RetainFragment mRetainFragment = RetainFragment.findOrCreateRetainFragment(getFragmentManager());  
  6.     mMemoryCache = RetainFragment.mRetainedCache;  
  7.     if (mMemoryCache == null) {  
  8.         mMemoryCache = new LruCache<string, bitmap="">(cacheSize) {  
  9.             ... // Initialize cache here as usual  
  10.         }  
  11.         mRetainFragment.mRetainedCache = mMemoryCache;  
  12.     }  
  13.     ...  
  14. }                   
  15. class RetainFragment extends Fragment {  
  16.     private static final String TAG = "RetainFragment";  
  17.     public LruCache<string, bitmap=""> mRetainedCache;  
  18.  
  19.     public RetainFragment() {}                   
  20.     public static RetainFragment findOrCreateRetainFragment(FragmentManager fm) {  
  21.         RetainFragment fragment = (RetainFragment) fm.findFragmentByTag(TAG);  
  22.         if (fragment == null) {  
  23.             fragment = new RetainFragment();  
  24.         }  
  25.         return fragment;  
  26.     }                   
  27.     @Override  
  28.     public void onCreate(Bundle savedInstanceState) {  
  29.         super.onCreate(savedInstanceState);  
  30.         <strong>setRetainInstance(true);</strong>  
  31.     }  
  32.  

此外您可以嘗試分別使用和不使用Fragment來旋轉(zhuǎn)設(shè)備的屏幕方向來查看具體的圖片載入情況。

責(zé)任編輯:龐桂玉 來源: Android開發(fā)中文站
相關(guān)推薦

2013-03-26 14:21:04

Android緩存Bitmap緩存池

2021-09-01 06:48:16

AndroidGlide緩存

2010-02-03 15:59:08

Android組件

2010-01-28 10:31:32

Android使用SD

2024-11-21 07:00:00

線程池Java開發(fā)

2014-12-31 09:45:48

EhCache

2018-05-28 08:54:45

SparkRDD Cache緩存

2011-09-13 17:03:16

Eclipse And

2013-07-10 15:52:17

fragmentAndroid

2019-03-20 09:11:50

Web緩存策略

2010-11-09 17:19:41

2021-03-29 11:51:07

緩存儲(chǔ)存數(shù)據(jù)

2014-10-13 10:15:13

Android HOOCydia Subst

2010-01-28 17:07:03

Android Gal

2015-04-27 09:50:45

Java Hibern連接池詳解

2011-06-09 11:36:00

java

2021-07-07 10:31:19

對(duì)象池模式解釋器模式設(shè)計(jì)模式

2024-12-04 15:55:19

2010-08-04 10:17:17

Android開發(fā)WebView組件

2010-12-12 21:01:00

Android控件
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)