Android高效顯示圖片詳解

用戶在使用ListView或GridView時,控件會自動把用戶滑過的已不在當前顯示區域的ChildView回收掉,固然也會把該子視圖上的bitmap回收掉以釋放內存,所以,爲了保證一個流暢,快速的操做體驗,咱們應當避免反覆的對同一張圖片進行加載,好比說用戶在往下看圖的過程當中又向上滑回去看圖,這時對於已經上面已經加載過的圖片咱們就沒有必要讓它再加載一遍了,應該能很快的把圖片顯示出來,這裏咱們要使用緩存來達到這一目的。


html

一,使用Memory Cache:緩存

內存緩存速度快,同時爲了更加適應實際應用的場景,咱們使用LruCache來達到按使用頻率緩存的目的,把最近使用的加入緩存,較長時間不用的則會剔除掉釋放出空間。app

緩存的代碼以下:ide

  1. private LruCache<String, Bitmap> mMemoryCache;  
  2.  
  3. @Override  
  4. protected void onCreate(Bundle savedInstanceState) {  
  5.    ...  
  6.    // Get max available VM memory, exceeding this amount will throw an  
  7.    // OutOfMemory exception. Stored in kilobytes as LruCache takes an  
  8.    // int in its constructor.  
  9.    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);  
  10.  
  11.    // Use 1/8th of the available memory for this memory cache.  
  12.    final int cacheSize = maxMemory / 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 kilobytes rather than  
  18.            // number of items.  
  19.            return bitmap.getByteCount() / 1024;  
  20.        }  
  21.    };  
  22.    ...  
  23. }  
  24.  
  25. public void addBitmapToMemoryCache(String key, Bitmap bitmap) {  
  26.    if (getBitmapFromMemCache(key) == null) {  
  27.        mMemoryCache.put(key, bitmap);  
  28.    }  
  29. }  
  30.  
  31. public Bitmap getBitmapFromMemCache(String key) {  
  32.    return mMemoryCache.get(key);  
  33. }  
private LruCache<String, Bitmap> mMemoryCache;

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    // Get max available VM memory, exceeding this amount will throw an
    // OutOfMemory exception. Stored in kilobytes as LruCache takes an
    // int in its constructor.
    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

    // Use 1/8th of the available memory for this memory cache.
    final int cacheSize = maxMemory / 8;

    mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            // The cache size will be measured in kilobytes rather than
            // number of items.
            return bitmap.getByteCount() / 1024;
        }
    };
    ...
}

public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
    if (getBitmapFromMemCache(key) == null) {
        mMemoryCache.put(key, bitmap);
    }
}

public Bitmap getBitmapFromMemCache(String key) {
    return mMemoryCache.get(key);
}


那麼咱們在loadBitmap的時候就能夠先檢查下緩存中保存的是否有該圖片,有則直接取出使用,再也不進行加載。ui

新的代碼以下:this

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

    final Bitmap bitmap = getBitmapFromMemCache(imageKey);
    if (bitmap != null) {
        mImageView.setImageBitmap(bitmap);
    } else {
        mImageView.setImageResource(R.drawable.image_placeholder);
        BitmapWorkerTask task = new BitmapWorkerTask(mImageView);
        task.execute(resId);
    }
}


固然,咱們也要在加載圖片是及時的維護緩存,把剛使用到的圖片add進緩存中去。spa

新的代碼以下:.net

  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. }  
class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
    ...
    // Decode image in background.
    @Override
    protected Bitmap doInBackground(Integer... params) {
        final Bitmap bitmap = decodeSampledBitmapFromResource(
                getResources(), params[0], 100, 100));
        addBitmapToMemoryCache(String.valueOf(params[0]), bitmap);
        return bitmap;
    }
    ...
}


在使用內存作緩存的基礎上,咱們還可使用Disk控件作爲緩存,構成一種二級緩存的結構,設想這種狀況,若是App在使用的過程被忽然來電打斷,那麼此時有可能就會引發系統內存的回收,當用戶再次切換到App時,App就要進行次很明顯的圖片再次加載的過程。這個時候,咱們就須要用到Disk了,由於足夠持久。code

下面是是原來的基礎上增長使用Disk Cache 的例子:orm

  1. private DiskLruCache mDiskLruCache;  
  2. private final Object mDiskCacheLock = new Object();  
  3. private boolean mDiskCacheStarting = true;  
  4. private static final int DISK_CACHE_SIZE = 1024 * 1024 * 10; // 10MB  
  5. private static final String DISK_CACHE_SUBDIR = "thumbnails";  
  6.  
  7. @Override  
  8. protected void onCreate(Bundle savedInstanceState) {  
  9.    ...  
  10.    // Initialize memory cache  
  11.    ...  
  12.    // Initialize disk cache on background thread  
  13.    File cacheDir = getDiskCacheDir(this, DISK_CACHE_SUBDIR);  
  14.    new InitDiskCacheTask().execute(cacheDir);  
  15.    ...  
  16. }  
  17.  
  18. class InitDiskCacheTask extends AsyncTask<File, Void, Void> {  
  19.    @Override  
  20.    protected Void doInBackground(File... params) {  
  21.        synchronized (mDiskCacheLock) {  
  22.            File cacheDir = params[0];  
  23.            mDiskLruCache = DiskLruCache.open(cacheDir, DISK_CACHE_SIZE);  
  24.            mDiskCacheStarting = false; // Finished initialization  
  25.            mDiskCacheLock.notifyAll(); // Wake any waiting threads  
  26.        }  
  27.        return null;  
  28.    }  
  29. }  
  30.  
  31. class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {  
  32.    ...  
  33.    // Decode image in background.  
  34.    @Override  
  35.    protected Bitmap doInBackground(Integer... params) {  
  36.        final String imageKey = String.valueOf(params[0]);  
  37.  
  38.        // Check disk cache in background thread  
  39.        Bitmap bitmap = getBitmapFromDiskCache(imageKey);  
  40.  
  41.        if (bitmap == null) { // Not found in disk cache  
  42.            // Process as normal  
  43.            final Bitmap bitmap = decodeSampledBitmapFromResource(  
  44.                    getResources(), params[0], 100, 100));  
  45.        }  
  46.  
  47.        // Add final bitmap to caches  
  48.        addBitmapToCache(imageKey, bitmap);  
  49.  
  50.        return bitmap;  
  51.    }  
  52.    ...  
  53. }  
  54.  
  55. public void addBitmapToCache(String key, Bitmap bitmap) {  
  56.    // Add to memory cache as before  
  57.    if (getBitmapFromMemCache(key) == null) {  
  58.        mMemoryCache.put(key, bitmap);  
  59.    }  
  60.  
  61.    // Also add to disk cache  
  62.    synchronized (mDiskCacheLock) {  
  63.        if (mDiskLruCache != null && mDiskLruCache.get(key) == null) {  
  64.            mDiskLruCache.put(key, bitmap);  
  65.        }  
  66.    }  
  67. }  
  68.  
  69. public Bitmap getBitmapFromDiskCache(String key) {  
  70.    synchronized (mDiskCacheLock) {  
  71.        // Wait while disk cache is started from background thread  
  72.        while (mDiskCacheStarting) {  
  73.            try {  
  74.                mDiskCacheLock.wait();  
  75.            } catch (InterruptedException e) {}  
  76.        }  
  77.        if (mDiskLruCache != null) {  
  78.            return mDiskLruCache.get(key);  
  79.        }  
  80.    }  
  81.    return null;  
  82. }  
  83.  
  84. // Creates a unique subdirectory of the designated app cache directory. Tries to use external  
  85. // but if not mounted, falls back on internal storage.  
  86. public static File getDiskCacheDir(Context context, String uniqueName) {  
  87.    // Check if media is mounted or storage is built-in, if so, try and use external cache dir  
  88.    // otherwise use internal cache dir  
  89.    final String cachePath =  
  90.            Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||  
  91.                    !isExternalStorageRemovable() ? getExternalCacheDir(context).getPath() :  
  92.                            context.getCacheDir().getPath();  
  93.  
  94.    return new File(cachePath + File.separator + uniqueName);  
  95. }  
相關文章
相關標籤/搜索