成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

Android中Bitmap緩存池

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

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

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

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

使用內存緩存

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

注意: 過去,實現內存緩存的常用做法是使用
SoftReference 或者
WeakReference bitmap 緩存,
但是不推薦使用這種方式。從Android 2.3 (API Level 9) 開始,垃圾回收開始強制的回收掉 soft/weak 引用 從而導致這些緩存沒有任何效率的提升。
另外,在 Android 3.0 (API Level 11)之前,這些緩存的Bitmap數據保存在底層內存(native memory)中,并且達到預定條件后也不會釋放這些對象,從而可能導致
程序超過內存限制并崩潰。

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

  • 程序中還有多少內存可用

  • 同時在屏幕上顯示多少圖片?要先緩存多少圖片用來顯示到即將看到的屏幕上?

  • 設備的屏幕尺寸和屏幕密度是多少?超高的屏幕密度(xhdpi 例如 Galaxy Nexus)
    設備顯示同樣的圖片要比低屏幕密度(hdpi 例如 Nexus S)設備需要更多的內存。

  • 圖片的尺寸和格式決定了每個圖片需要占用多少內存

  • 圖片訪問的頻率如何?一些圖片的訪問頻率要比其他圖片高很多?如果是這樣的話,您可能需要把這些經常訪問的圖片放到內存中。

  • 在質量和數量上如何平衡?有些情況下保存大量的低質量的圖片是非常有用的,當需要的情況下使用后臺線程來加入一個高質量版本的圖片。

這里沒有萬能配方可以適合所有的程序,您需要分析您的使用情況并在指定自己的緩存策略。使用太小的緩存并不能起到應有的效果,而使用太大的緩存會消耗更多
的內存從而有可能導致 java.lang.OutOfMemory 異常或者留下很少的內存供您的程序其他功能使用。

下面是一個使用 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); 

注意: 在這個示例中,該程序的1/8內存都用來做緩存用了。在一個normal/hdpi設備中,這至少有4MB(32/8)內存。
在一個分辨率為 800×480的設備中,滿屏的GridView全部填充上圖片將會使用差不多1.5MB(800*480*4 bytes)
的內存,所以這樣差不多在內存中緩存了2.5頁的圖片。

當在 ImageView 中顯示圖片的時候,
先檢查LruCache 中是否存在。如果存在就使用緩存后的圖片,如果不存在就啟動后臺線程去載入圖片并緩存:

  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.     } 

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], 100100)); 
  8.         addBitmapToMemoryCache(String.valueOf(params[0]), bitmap); 
  9.         return bitmap; 
  10.     } 
  11.     ... 

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

#p#

使用磁盤緩存

在訪問最近使用過的圖片中,內存緩存速度很快,但是您無法確定圖片是否在緩存中存在。像
GridView 這種控件可能具有很多圖片需要顯示,很快圖片數據就填滿了緩存容量。
同時您的程序還可能被其他任務打斷,比如打進的電話 — 當您的程序位于后臺的時候,系統可能會清楚到這些圖片緩存。一旦用戶恢復使用您的程序,您還需要重新處理這些圖片。

在這種情況下,可以使用磁盤緩存來保存這些已經處理過的圖片,當這些圖片在內存緩存中不可用的時候,可以從磁盤緩存中加載從而省略了圖片處理過程。
當然, 從磁盤載入圖片要比從內存讀取慢很多,并且應該在非UI線程中載入磁盤圖片。

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

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

這里是一個更新版本的 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], 100100)); 
  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); 

在UI線程中檢測內存緩存,在后臺線程中檢測磁盤緩存。磁盤操作從來不應該在UI線程中實現。當圖片處理完畢后,最終的結果會同時添加到
內存緩存和磁盤緩存中以便將來使用。

處理配置改變事件

運行時的配置變更 — 例如 屏幕方向改變 — 導致Android摧毀正在運行的Activity,然后使用
新的配置從新啟動該Activity (詳情,參考這里 Handling Runtime Changes)。
您需要注意避免在配置改變的時候導致重新處理所有的圖片,從而提高用戶體驗。

幸運的是,您在 使用內存緩存 部分已經有一個很好的圖片緩存了。該緩存可以通過
Fragment (Fragment會通過setRetainInstance(true)函數保存起來)來傳遞給新的Activity
當Activity重新啟動 后,Fragment 被重新附加到Activity中,您可以通過該Fragment來獲取緩存對象。

下面是一個在 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.     } 

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

責任編輯:閆佳明 來源: cnblogs
相關推薦

2017-02-17 11:50:18

AndroidBitmap緩存池

2023-11-16 08:22:14

LruCacheAndroid

2013-07-29 16:22:21

Android緩存框架

2013-05-21 10:42:48

Android游戲開發Bitmap位圖旋轉

2013-09-16 16:56:09

AndroidBitmap內存優化

2024-12-13 08:21:04

2021-03-29 11:51:07

緩存儲存數據

2020-07-29 09:13:28

JavaScript開發技術

2019-07-02 15:21:39

緩存NET單線程

2017-12-08 08:58:46

微模塊機房服務器

2020-06-18 09:16:20

JavaScript緩存API

2022-07-07 08:02:49

RedisBitMap

2023-04-26 08:39:41

Bitmap元素存儲

2021-01-06 17:28:00

MySQL數據庫緩存池

2024-03-15 07:17:51

MySQLLRU算法緩存池

2018-10-26 15:54:16

JavaClass常量池

2011-06-01 09:03:12

Android 緩存

2020-01-10 15:42:13

SpringBootRedis數據庫

2024-08-26 14:46:57

2019-09-29 10:29:02

緩存模式微服務架構
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 婷婷成人在线 | 久久99蜜桃综合影院免费观看 | av中文在线 | 欧美日韩a | 成人精品一区二区 | 久久久久无码国产精品一区 | 99精品欧美一区二区蜜桃免费 | 日本午夜网站 | 日韩欧美三级 | 一区二区成人在线 | 日本aaaa| 色婷婷综合久久久久中文一区二区 | 国产91综合 | 亚洲精品久久久一区二区三区 | 黄色a三级 | 精品国产一区二区在线 | 91xxx在线观看 | 一区二区三区视频免费看 | 日韩久久久一区二区 | 久久久高清 | 99久久婷婷国产综合精品 | 五月精品视频 | 国产丝袜人妖cd露出 | 高清av电影| 亚洲精品久久久9婷婷中文字幕 | 亚洲一区二区三区在线观看免费 | 久久不射电影网 | 亚洲福利在线观看 | 精品久久久久久亚洲综合网 | 日韩三级 | 国产精品3区 | 欧美在线视频一区 | 国产激情视频在线观看 | 亚洲精品黄色 | 少妇一级淫片免费放播放 | 欧美 日韩 中文 | 亚洲精品www久久久久久广东 | 青青草av在线播放 | 亚洲视频一区在线观看 | 欧美二级 | 日韩三区在线观看 |