Примечание. В большинстве случаев мы рекомендуем использовать библиотеку Glide для получения, декодирования и отображения растровых изображений в приложении. Glide абстрагирует большую часть сложности при обработке этих и других задач, связанных с работой с растровыми и другими изображениями на Android. Информацию о том, как использовать и скачать Glide, можно найти в хранилище Glide на GitHub.
Помимо действий, описанных в разделе Кеширование растровых изображений, вы можете предпринять определенные шаги, чтобы упростить сборку мусора и повторное использование растровых изображений. Рекомендуемая стратегия зависит от того, на какие версии Android вы ориентируетесь. Пример приложения BitmapFun, включенный в этот курс, показывает, как разработать приложение, которое будет эффективно работать в разных версиях Android.
Чтобы лучше понять материал этого урока, ознакомьтесь с тем, как развивалось управление памятью битовых карт в Android:
- В Android 2.2 (уровень API 8) и более ранних версиях при сборке мусора потоки приложения останавливаются. Это вызывает задержку, которая может снизить производительность. В Android 2.3 добавлена параллельная сборка мусора, то есть память освобождается вскоре после того, как на растровое изображение больше не ссылаются.
- В Android 2.3.3 (уровень API 10) и более ранних версиях данные пикселей для битовой карты хранятся в нативной памяти. Он отделен от самого растрового изображения, которое хранится в куче Dalvik. Данные пикселей в нативной памяти не освобождаются предсказуемым образом, что может привести к кратковременному превышению лимитов памяти приложения и его сбою. В версиях Android от 3.0 (уровень API 11) до 7.1 (уровень API 25) данные пикселей хранятся в куче Dalvik вместе со связанной битовой картой. В Android 8.0 (уровень API 26) и более поздних версиях пиксельные данные растрового изображения хранятся в нативной куче.
В следующих разделах описывается, как оптимизировать управление памятью битовых карт для разных версий Android.
Как управлять памятью на устройствах с Android 2.3.3 и более ранними версиями
На устройствах с Android 2.3.3 (уровень API 10) и более ранними версиями рекомендуется использовать recycle(). Если в приложении отображается большой объем растровых данных, вы, скорее всего, столкнетесь с ошибками OutOfMemoryError. Метод recycle() позволяет приложению как можно быстрее освободить память.
Внимание! Метод recycle() следует использовать, только если вы уверены, что битовая карта больше не используется. Если вы вызовете recycle(), а затем попытаетесь нарисовать растровое изображение, то получите ошибку "Canvas: trying to use a recycled bitmap".
В приведенном ниже фрагменте кода показан пример вызова recycle(). Для отслеживания того, отображается ли растровое изображение или находится в кеше, используется подсчет ссылок (в переменных mDisplayRefCount и mCacheRefCount). Код повторно использует битовую карту, если выполняются следующие условия:
- Количество ссылок для
mDisplayRefCountиmCacheRefCountравно 0. - Битовая карта не является
nullи ещё не была утилизирована.
Kotlin
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
Java
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 3.0 и более поздних версиях
В Android 3.0 (уровень API 11) появилось поле BitmapFactory.Options.inBitmap. Если этот параметр задан, методы декодирования, которые принимают объект Options, будут пытаться повторно использовать существующую битовую карту при загрузке контента. Это означает, что память битовой карты используется повторно, что приводит к повышению производительности и удалению как выделения памяти, так и ее освобождения. Однако на использование inBitmap накладываются определенные ограничения. В частности, до Android 4.4 (уровень API 19) поддерживаются только растровые изображения одинакового размера. Подробную информацию можно найти в документации по inBitmap.
Как сохранить растровое изображение для дальнейшего использования
В следующем фрагменте кода показано, как существующая битовая карта сохраняется для возможного последующего использования в примере приложения. Когда приложение работает на Android 3.0 или более поздней версии и битовая карта удаляется из LruCache, мягкая ссылка на битовую карту помещается в HashSet для возможного повторного использования позже с inBitmap:
Kotlin
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)) } } } }
Java
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())); } } } .... }
Использовать существующую битовую карту
В работающем приложении методы декодера проверяют, есть ли существующая битовая карта, которую они могут использовать. Пример:
Kotlin
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) }
Java
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, только если находит подходящее соответствие (не следует рассчитывать на то, что соответствие будет найдено всегда):
Kotlin
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 }
Java
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:
Kotlin
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 } }
Java
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; }