Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

原始碼解析:Android Drawable 的享元與快取機制

編輯:關於 Android 程式設計

在 Android 中,我們通常透過 Resources.getDrawable(int) 取得 Drawable 物件,Framework 會回傳一個頂層抽象的 Drawable。有趣的是,系統在背後用了「享元(Flyweight)」的方式來節省記憶體。我們先寫個小 demo 來驗證這個說法。

首先在專案裡放一張 test.png,然後定義一個簡單的 Activity 並覆寫 onCreate:

List list = new ArrayList(); Bitmap bitmap = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); for (int i = 0; i < 10; i ++) { bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.test); list.add(bitmap); } ImageView iv = new ImageView(this); iv.setImageBitmap(bitmap); this.setContentView(iv); }

這裡用 list 把 Bitmap 存起來,是為了避免被 GC 回收而干擾測量。印出記憶體後會發現,10 個 Bitmap 實際佔用了約 26364K。接著改用 Drawable 的方式:

List list = new ArrayList(); Drawable bitmap = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); for (int i = 0; i < 10; i ++) { bitmap = this.getResources().getDrawable(R.drawable.test); list.add(bitmap); } ImageView iv = new ImageView(this); iv.setImageDrawable(bitmap); this.setContentView(iv); }

再印一次記憶體,數字降到了約 7844K,基本印證了我們的推論。那麼,會不會是 Resources 直接快取了相同的 Drawable 呢?其實並不是,你可以這樣測試:

Drawable d1 = this.getResources().getDrawable(R.drawable.test); Drawable d2 = this.getResources().getDrawable(R.drawable.test); System.out.println(">>>d1 == d2 ? = "+(d1 == d2));

輸出結果是 false。也就是說,享元這點毋庸置疑,但 Framework 在包裝 Drawable 時還引入了「組合模式」,真正被快取的是 Drawable 的核心元資料。

Resources.java Drawable loadDrawable(TypedValue value, int id) throws NotFoundException { ... Drawable dr = getCachedDrawable(isColorDrawable ? mColorDrawableCache : mDrawableCache, key); ... }

從程式碼可見,系統把 Drawable 主要分成兩大類(還有一類是預先載入型,這裡不深入討論)。由於我們載入的不屬於 color 類型,因此對應的享元池由 mDrawableCache 負責。

Resources.java private Drawable getCachedDrawable( LongSparseArray> drawableCache, long key) { synchronized (mAccessLock) { WeakReference wr = drawableCache.get(key); if (wr != null) { Drawable.ConstantState entry = wr.get(); if (entry != null) { return entry.newDrawable(this); } else { drawableCache.delete(key); } } } return null; }

由此可見,真正存進池子裡的並不是 Drawable 本身,而是 Drawable.ConstantState 型別的物件,而且還用弱引用包起來。ConstantState 是一個抽象類,擁有多個子類實作:

public static abstract class ConstantState { public abstract Drawable newDrawable(); public Drawable newDrawable(Resources res) { return newDrawable(); } public abstract int getChangingConfigurations(); public Bitmap getBitmap() { return null; } }

我們使用的是 BitmapDrawable,它對應的 ConstantState 是 BitmapState:

final static class BitmapState extends ConstantState { Bitmap mBitmap; int mChangingConfigurations; int mGravity = Gravity.FILL; Paint mPaint = new Paint(DEFAULT_PAINT_FLAGS); Shader.TileMode mTileModeX = null; Shader.TileMode mTileModeY = null; int mTargetDensity = DisplayMetrics.DENSITY_DEFAULT; boolean mRebuildShader; boolean mAutoMirrored; BitmapState(Bitmap bitmap) { mBitmap = bitmap; } BitmapState(BitmapState bitmapState) { this(bitmapState.mBitmap); mChangingConfigurations = bitmapState.mChangingConfigurations; mGravity = bitmapState.mGravity; mTileModeX = bitmapState.mTileModeX; mTileModeY = bitmapState.mTileModeY; mTargetDensity = bitmapState.mTargetDensity; mPaint = new Paint(bitmapState.mPaint); mRebuildShader = bitmapState.mRebuildShader; mAutoMirrored = bitmapState.mAutoMirrored; } @Override public Bitmap getBitmap() { return mBitmap; } @Override public Drawable newDrawable() { return new BitmapDrawable(this, null); } @Override public Drawable newDrawable(Resources res) { return new BitmapDrawable(this, res); } @Override public int getChangingConfigurations() { return mChangingConfigurations; } }

可以注意到 BitmapState 的 newDrawable() 會把自己當參數傳給 BitmapDrawable,也就是說每個 BitmapDrawable 都組合了同一個 BitmapState,這就實現了同一張 Bitmap 資源的复用。

了解如何取出之後,我們再來看 ConstantState 是怎麼被存進快取的:

Resources.loadDrawable() { ... InputStream is = mAssets.openNonAsset( value.assetCookie, file, AssetManager.ACCESS_STREAMING); dr = createFromResourceStream(this, value, is, file, id); is.close(); ... if (dr != null) { dr.setChangingConfigurations(value.changingConfigurations); cs = dr.getConstantState(); if (cs != null) { if (mPreloading) { ... } else { synchronized (mAccessLock) { if (isColorDrawable) { mColorDrawableCache.put(key, new WeakReference(cs)); } else { mDrawableCache.put(key, new WeakReference(cs)); } } } } ... }

由此可見,每當產生一個新的 Drawable,系統就會把它的 ConstantState 取出並放進快取池中,供後續復用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved