توجه: در اکثر موارد، توصیه میکنیم از کتابخانه Glide برای واکشی، رمزگشایی، و نمایش بیتمپها در برنامهتان استفاده کنید. Glide اکثر پیچیدگیهای مربوط به مدیریت این موارد و سایر کارهای مرتبط با کار با بیتمپها و تصاویر دیگر در Android را خلاصه میکند. برای کسب اطلاعات درباره استفاده و بارگیری Glide، به مخزن Glide در GitHub مراجعه کنید.
علاوهبر مراحل شرحدادهشده در ذخیره کردن نقشههای بیتی در حافظه نهان،
کارهای خاصی وجود دارد که میتوانید برای تسهیل جمعآوری زباله
و استفاده مجدد از نقشه بیتی انجام دهید. استراتژی توصیهشده به نسخه(های) Android که هدف قرار میدهید بستگی دارد. برنامه نمونه BitmapFun که در این کلاس گنجانده شده است به شما نشان میدهد که چگونه برنامهتان را طراحی کنید تا بهطور مؤثر در نسخههای مختلف Android کار کند.
برای آماده کردن زمینه برای این درس، در اینجا نحوه تکامل مدیریت Android بر حافظه نگاشت بیتی آورده شده است:
- در Android 2.2 (سطح میانای برنامهسازی کاربردی ۸) و پایینتر، وقتی جمعآوری زباله اتفاق میافتد، رشتههای برنامهتان متوقف میشود. این کار باعث تأخیری میشود که میتواند عملکرد را کاهش دهد. Android 2.3 جمعآوری زباله همزمان را اضافه میکند، به این معنی که حافظه بلافاصله پساز اینکه دیگر به نقشه بیتی ارجاع داده نشود، بازیابی میشود.
- در Android 2.3.3 (سطح میانای برنامه کاربردی ۱۰) و پایینتر، دادههای پیکسل پشتیبان برای نقشه بیتی در حافظه بومی ذخیره میشود. این شیء از خود نقشه بیتی که در پشته Dalvik ذخیره میشود جدا است. دادههای پیکسل در حافظه بومی بهصورت قابلپیشبینی منتشر نمیشود، که این امر میتواند باعث شود برنامه بهطور موقت از محدودیتهای حافظه خود فراتر رود و ازکار بیفتد. از Android 3.0 (سطح API ۱۱) تا Android 7.1 (سطح API ۲۵)، دادههای پیکسل در توده Dalvik بههمراه نقشه بیتی مربوطه ذخیره میشود. در Android نسخه ۸.۰ (سطح میانای برنامهسازی کاربردی ۲۶) و بالاتر، دادههای پیکسل نقشه بیتی در توده بومی ذخیره میشود.
بخشهای زیر نحوه بهینهسازی مدیریت حافظه نگاشت بیتی را برای نسخههای مختلف Android شرح میدهد.
مدیریت حافظه در Android 2.3.3 و نسخههای پایینتر
در Android 2.3.3 (سطح میانای برنامهسازی کاربردی ۱۰) و پایینتر، استفاده از
recycle()
توصیه میشود. اگر مقدار زیادی داده نگاشت بیتی در برنامهتان نمایش میدهید،
احتمالاً با خطاهای
OutOfMemoryError مواجه خواهید شد. روش
recycle() به برنامه اجازه میدهد
در اسرع وقت حافظه را پس بگیرد.
احتیاط: باید از
recycle() فقط زمانی استفاده کنید که مطمئن هستید
دیگر از نقشه بیتی استفاده نمیشود. اگر recycle() را فراخوانی کنید
و بعداً تلاش کنید نقشه بیتی را ترسیم کنید، این خطا را دریافت خواهید کرد:
"Canvas: trying to use a recycled bitmap".
تکهکد زیر نمونهای از فراخوانی
recycle() را ارائه میدهد. این کلاس از شمارش مرجع
(در متغیرهای mDisplayRefCount و mCacheRefCount) برای ردیابی
اینکه آیا نقشه بیتی درحالحاضر نمایش داده میشود یا در حافظه نهان است استفاده میکند. وقتی این شرایط برقرار باشد، کد
نقشه بیتی را بازیافت میکند:
- تعداد ارجاع برای هر دو
mDisplayRefCountوmCacheRefCountبرابر با ۰ است. - بیتمپ
nullنیست و هنوز بازیافت نشده است.
کاتلین
private var cacheRefCount: Int = 0 private var displayRefCount: Int = 0 ... // Notify the drawable that the displayed state has changed. // Keep a count to determine when the drawable is no longer displayed. fun setIsDisplayed(isDisplayed: Boolean) { synchronized(this) { if (isDisplayed) { displayRefCount++ hasBeenDisplayed = true } else { displayRefCount-- } } // Check to see if recycle() can be called. checkState() } // Notify the drawable that the cache state has changed. // Keep a count to determine when the drawable is no longer being cached. fun setIsCached(isCached: Boolean) { synchronized(this) { if (isCached) { cacheRefCount++ } else { cacheRefCount-- } } // Check to see if recycle() can be called. checkState() } @Synchronized private fun checkState() { // If the drawable cache and display ref counts = 0, and this drawable // has been displayed, then recycle. if (cacheRefCount <= 0 && displayRefCount <= 0 && hasBeenDisplayed && hasValidBitmap() ) { getBitmap()?.recycle() } } @Synchronized private fun hasValidBitmap(): Boolean = getBitmap()?.run { !isRecycled } ?: false
جاوا
private int cacheRefCount = 0; private int displayRefCount = 0; ... // Notify the drawable that the displayed state has changed. // Keep a count to determine when the drawable is no longer displayed. public void setIsDisplayed(boolean isDisplayed) { synchronized (this) { if (isDisplayed) { displayRefCount++; hasBeenDisplayed = true; } else { displayRefCount--; } } // Check to see if recycle() can be called. checkState(); } // Notify the drawable that the cache state has changed. // Keep a count to determine when the drawable is no longer being cached. public void setIsCached(boolean isCached) { synchronized (this) { if (isCached) { cacheRefCount++; } else { cacheRefCount--; } } // Check to see if recycle() can be called. checkState(); } private synchronized void checkState() { // If the drawable cache and display ref counts = 0, and this drawable // has been displayed, then recycle. if (cacheRefCount <= 0 && displayRefCount <= 0 && hasBeenDisplayed && hasValidBitmap()) { getBitmap().recycle(); } } private synchronized boolean hasValidBitmap() { Bitmap bitmap = getBitmap(); return bitmap != null && !bitmap.isRecycled(); }
مدیریت حافظه در Android نسخه ۳.۰ و بالاتر
Android 3.0 (سطح میانای برنامهسازی کاربردی ۱۱) فیلد
BitmapFactory.Options.inBitmap
را معرفی میکند. اگر این گزینه تنظیم شده باشد، روشهای رمزگشایی که
شیء Options را میگیرند
هنگام بار کردن محتوا تلاش میکنند از نقشه بیتی موجود مجدداً استفاده کنند. این یعنی
حافظه بیتمپ دوباره استفاده میشود، که منجر به بهبود عملکرد میشود، و
هم تخصیص حافظه و هم لغو تخصیص حافظه را حذف میکند. اما محدودیتهای خاصی درباره نحوه استفاده از
inBitmap وجود دارد. بهویژه، قبلاز Android نسخه
4.4 (سطح میانای برنامهسازی کاربردی ۱۹)، فقط نقشههای بیتی با اندازه برابر پشتیبانی میشوند. برای جزئیات، لطفاً
اسناد inBitmap را ببینید.
ذخیره کردن نقشه بیتی برای استفاده در آینده
قطعه کد زیر نشان میدهد که چگونه یک بیتمپ موجود برای استفاده احتمالی بعدی در برنامه نمونه ذخیره میشود. وقتی برنامهای در Android نسخه ۳.۰ یا بالاتر اجرا میشود و یک بیتمپ از LruCache حذف میشود، یک ارجاع نرم به بیتمپ در یک HashSet قرار میگیرد تا احتمالاً بعداً با inBitmap دوباره استفاده شود:
کاتلین
var reusableBitmaps: MutableSet<SoftReference<Bitmap>>? = null private lateinit var memoryCache: LruCache<String, BitmapDrawable> // If you're running on Honeycomb or newer, create a // synchronized HashSet of references to reusable bitmaps. if (Utils.hasHoneycomb()) { reusableBitmaps = Collections.synchronizedSet(HashSet<SoftReference<Bitmap>>()) } memoryCache = object : LruCache<String, BitmapDrawable>(cacheParams.memCacheSize) { // Notify the removed entry that is no longer being cached. override fun entryRemoved( evicted: Boolean, key: String, oldValue: BitmapDrawable, newValue: BitmapDrawable ) { if (oldValue is RecyclingBitmapDrawable) { // The removed entry is a recycling drawable, so notify it // that it has been removed from the memory cache. oldValue.setIsCached(false) } else { // The removed entry is a standard BitmapDrawable. if (Utils.hasHoneycomb()) { // We're running on Honeycomb or later, so add the bitmap // to a SoftReference set for possible use with inBitmap later. reusableBitmaps?.add(SoftReference(oldValue.bitmap)) } } } }
جاوا
Set<SoftReference<Bitmap>> reusableBitmaps; private LruCache<String, BitmapDrawable> memoryCache; // If you're running on Honeycomb or newer, create a // synchronized HashSet of references to reusable bitmaps. if (Utils.hasHoneycomb()) { reusableBitmaps = Collections.synchronizedSet(new HashSet<SoftReference<Bitmap>>()); } memoryCache = new LruCache<String, BitmapDrawable>(cacheParams.memCacheSize) { // Notify the removed entry that is no longer being cached. @Override protected void entryRemoved(boolean evicted, String key, BitmapDrawable oldValue, BitmapDrawable newValue) { if (RecyclingBitmapDrawable.class.isInstance(oldValue)) { // The removed entry is a recycling drawable, so notify it // that it has been removed from the memory cache. ((RecyclingBitmapDrawable) oldValue).setIsCached(false); } else { // The removed entry is a standard BitmapDrawable. if (Utils.hasHoneycomb()) { // We're running on Honeycomb or later, so add the bitmap // to a SoftReference set for possible use with inBitmap later. reusableBitmaps.add (new SoftReference<Bitmap>(oldValue.getBitmap())); } } } .... }
استفاده از بیتمپ موجود
در برنامه درحال اجرا، روشهای رمزگشا بررسی میکنند که آیا نقشه بیتی موجودی وجود دارد که بتوانند از آن استفاده کنند یا نه. برای مثال:
کاتلین
fun decodeSampledBitmapFromFile( filename: String, reqWidth: Int, reqHeight: Int, cache: ImageCache ): Bitmap { val options: BitmapFactory.Options = BitmapFactory.Options() ... BitmapFactory.decodeFile(filename, options) ... // If we're running on Honeycomb or newer, try to use inBitmap. if (Utils.hasHoneycomb()) { addInBitmapOptions(options, cache) } ... return BitmapFactory.decodeFile(filename, options) }
جاوا
public static Bitmap decodeSampledBitmapFromFile(String filename, int reqWidth, int reqHeight, ImageCache cache) { final BitmapFactory.Options options = new BitmapFactory.Options(); ... BitmapFactory.decodeFile(filename, options); ... // If we're running on Honeycomb or newer, try to use inBitmap. if (Utils.hasHoneycomb()) { addInBitmapOptions(options, cache); } ... return BitmapFactory.decodeFile(filename, options); }
تکهکد بعدی روش addInBitmapOptions() را نشان میدهد که در تکهکد بالا فراخوانی شده است. این کد بهدنبال نگاشت بیتی موجود میگردد تا آن را بهعنوان مقدار
inBitmap تنظیم کند. توجه داشته باشید که این
روش فقط درصورتی مقداری برای inBitmap تنظیم میکند
که مطابقت مناسبی پیدا کند (کد شما هرگز نباید فرض کند که مطابقت پیدا خواهد شد):
کاتلین
private fun addInBitmapOptions(options: BitmapFactory.Options, cache: ImageCache?) { // inBitmap only works with mutable bitmaps, so force the decoder to // return mutable bitmaps. options.inMutable = true // Try to find a bitmap to use for inBitmap. cache?.getBitmapFromReusableSet(options)?.also { inBitmap -> // If a suitable bitmap has been found, set it as the value of // inBitmap. options.inBitmap = inBitmap } } // This method iterates through the reusable bitmaps, looking for one // to use for inBitmap: fun getBitmapFromReusableSet(options: BitmapFactory.Options): Bitmap? { mReusableBitmaps?.takeIf { it.isNotEmpty() }?.let { reusableBitmaps -> synchronized(reusableBitmaps) { val iterator: MutableIterator<SoftReference<Bitmap>> = reusableBitmaps.iterator() while (iterator.hasNext()) { iterator.next().get()?.let { item -> if (item.isMutable) { // Check to see it the item can be used for inBitmap. if (canUseForInBitmap(item, options)) { // Remove from reusable set so it can't be used again. iterator.remove() return item } } else { // Remove from the set if the reference has been cleared. iterator.remove() } } } } } return null }
جاوا
private static void addInBitmapOptions(BitmapFactory.Options options, ImageCache cache) { // inBitmap only works with mutable bitmaps, so force the decoder to // return mutable bitmaps. options.inMutable = true; if (cache != null) { // Try to find a bitmap to use for inBitmap. Bitmap inBitmap = cache.getBitmapFromReusableSet(options); if (inBitmap != null) { // If a suitable bitmap has been found, set it as the value of // inBitmap. options.inBitmap = inBitmap; } } } // This method iterates through the reusable bitmaps, looking for one // to use for inBitmap: protected Bitmap getBitmapFromReusableSet(BitmapFactory.Options options) { Bitmap bitmap = null; if (reusableBitmaps != null && !reusableBitmaps.isEmpty()) { synchronized (reusableBitmaps) { final Iterator<SoftReference<Bitmap>> iterator = reusableBitmaps.iterator(); Bitmap item; while (iterator.hasNext()) { item = iterator.next().get(); if (null != item && item.isMutable()) { // Check to see it the item can be used for inBitmap. if (canUseForInBitmap(item, options)) { bitmap = item; // Remove from reusable set so it can't be used again. iterator.remove(); break; } } else { // Remove from the set if the reference has been cleared. iterator.remove(); } } } } return bitmap; }
درنهایت، این روش تعیین میکند که آیا نقشه بیتی نامزد
معیارهای اندازه را برای استفاده در
inBitmap برآورده میکند یا نه:
کاتلین
private fun canUseForInBitmap(candidate: Bitmap, targetOptions: BitmapFactory.Options): Boolean { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // From Android 4.4 (KitKat) onward we can re-use if the byte size of // the new bitmap is smaller than the reusable bitmap candidate // allocation byte count. val width = ceil((targetOptions.outWidth * 1.0f / targetOptions.inSampleSize).toDouble()).toInt() val height = ceil((targetOptions.outHeight * 1.0f / targetOptions.inSampleSize).toDouble()).toInt() val byteCount: Int = width * height * getBytesPerPixel(candidate.config) byteCount <= candidate.allocationByteCount } else { // On earlier versions, the dimensions must match exactly and the inSampleSize must be 1 candidate.width == targetOptions.outWidth && candidate.height == targetOptions.outHeight && targetOptions.inSampleSize == 1 } } /** * A helper function to return the byte usage per pixel of a bitmap based on its configuration. */ private fun getBytesPerPixel(config: Bitmap.Config): Int { return when (config) { Bitmap.Config.ARGB_8888 -> 4 Bitmap.Config.RGB_565, Bitmap.Config.ARGB_4444 -> 2 Bitmap.Config.ALPHA_8 -> 1 else -> 1 } }
جاوا
static boolean canUseForInBitmap( Bitmap candidate, BitmapFactory.Options targetOptions) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // From Android 4.4 (KitKat) onward we can re-use if the byte size of // the new bitmap is smaller than the reusable bitmap candidate // allocation byte count. int width = (int) Math.ceil(targetOptions.outWidth * 1.0f / targetOptions.inSampleSize); int height = (int) Math.ceil(targetOptions.outHeight * 1.0f / targetOptions.inSampleSize); int byteCount = width * height * getBytesPerPixel(candidate.getConfig()); return byteCount <= candidate.getAllocationByteCount(); } // On earlier versions, the dimensions must match exactly and the inSampleSize must be 1 return candidate.getWidth() == targetOptions.outWidth && candidate.getHeight() == targetOptions.outHeight && targetOptions.inSampleSize == 1; } /** * A helper function to return the byte usage per pixel of a bitmap based on its configuration. */ static int getBytesPerPixel(Config config) { if (config == Config.ARGB_8888) { return 4; } else if (config == Config.RGB_565) { return 2; } else if (config == Config.ARGB_4444) { return 2; } else if (config == Config.ALPHA_8) { return 1; } return 1; }