`
su1216
  • 浏览: 671955 次
  • 性别: Icon_minigender_1
  • 来自: 北京
博客专栏
Group-logo
深入入门正则表达式(jav...
浏览量:71998
E60283d7-4822-3dfb-9de4-f2377e30189c
android手机的安全问...
浏览量:128908
社区版块
存档分类
最新评论

android 管理Bitmap内存 - 开发文档翻译

阅读更多

由于本人英文能力实在有限,不足之初敬请谅解

本博客只要没有注明“转”,那么均为原创,转贴请注明本博客链接链接

 

Managing Bitmap Memory

管理Bitmap内存

 

In addition to the steps described in Caching Bitmaps, there are specific things you can do to facilitate garbage collection and bitmap reuse. 

The recommended strategy depends on which version(s) of Android you are targeting. 

The BitmapFun sample app included with this class shows you how to design your app to work efficiently across different versions of Android.

除了在Caching Bitmaps里描述的,还有一些具体的事情有助于垃圾回收和bitmap的重用

建议的策略取决于你针对的Android版本。

BitmapFun样本应用中包括这个类,它展示给你如何设计你的应用使得跨版本工作更有效率

 

To set the stage for this lesson, here is how Android's management of bitmap memory has evolved:

为课程打基础,下面是android的bitmap内存管理是如何演化的

 

On Android Android 2.2 (API level 8) and lower, when garbage collection occurs, your app's threads get stopped. 

This causes a lag that can degrade performance. 

Android 2.3 adds concurrent garbage collection, which means that the memory is reclaimed soon after a bitmap is no longer referenced.

在Android2.2(API 8)以及更低的版本中,当发生垃圾回收时,你的应用线程会停止。

这会导致延迟,使得性能降低

Android2.3添加了并发垃圾收集,这意为着一个bitmap不再被引用的时候,内存很快就被回收

 

On Android 2.3.3 (API level 10) and lower, the backing pixel data for a bitmap is stored in native memory. 

It is separate from the bitmap itself, which is stored in the Dalvik heap. 

The pixel data in native memory is not released in a predictable manner, potentially causing an application to briefly exceed its memory limits and crash. 

As of Android 3.0 (API Level 11), the pixel data is stored on the Dalvik heap along with the associated bitmap.

在Android2.3.3(API 10)和更低的版本中,bitmap的像素数据是存储在native内存中的

它独立于bitmap本身,bitmap是存储在Dalvik堆中的

在native内存中的bitmap的像素数据不会在一个可预测的行为之释放,潜在的导致应用内存超过限制并且崩溃

在android3.0(API 11)中,bitmap的像素数据存储在Dalvik堆中于bitmap相关联

 

The following sections describe how to optimize bitmap memory management for different Android versions.

下面章节讲述在不同的android版本中,如何最优化bitmap内存管理

 

 

Manage Memory on Android 2.3.3 and Lower

在android2.3.3以及更低的版本中管理内存

 

On Android 2.3.3 (API level 10) and lower, using recycle() is recommended. 

If you're displaying large amounts of bitmap data in your app, you're likely to run into OutOfMemoryError errors. 

The recycle() method allows an app to reclaim memory as soon as possible.

在android2.3.3以及更低的版本中,建议使用recycle()

如果你在你的应用中大量的显示bitmap数据,你很可能得到OutOfMemoryError错误

recycle()方法允许一个应用尽快回收内存

 

Caution: You should use recycle() only when you are sure that the bitmap is no longer being used. 

If you call recycle() and later attempt to draw the bitmap, you will get the error: "Canvas: trying to use a recycled bitmap".

注意:仅当你确定这个bitmap不会再被使用的时候,你才应该使用recycle()

如果你调用了recycle(),之后又试图绘制这个bitmap,你会得到 错误:“Canvas: trying to use a recycled bitmap”

 

The following code snippet gives an example of calling recycle(). 

It uses reference counting (in the variables mDisplayRefCount and mCacheRefCount) to track whether a bitmap is currently being displayed or in the cache. 

The code recycles the bitmap when these conditions are met:

下面的代码片断给出了一个调用recycle()例子

它使用引用计数(在变量mDisplayRefCount 和 mCacheRefCount中)来跟踪一个bitmap当前正在被显示还是在缓存中

代码回收bitmap需要的条件是:

 

The reference count for both mDisplayRefCount and mCacheRefCount is 0.

The bitmap is not null, and it hasn't been recycled yet.

引用计数mDisplayRefCount和mCacheRefCount都要=0

bitmap不为null,并且它还没有被回收

private int mCacheRefCount = 0;
private int mDisplayRefCount = 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) {
            mDisplayRefCount++;
            mHasBeenDisplayed = true;
        } else {
            mDisplayRefCount--;
        }
    }
    // 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) {
            mCacheRefCount++;
        } else {
            mCacheRefCount--;
        }
    }
    // 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 (mCacheRefCount <= 0 && mDisplayRefCount <= 0 && mHasBeenDisplayed
            && hasValidBitmap()) {
        getBitmap().recycle();
    }
}
 
private synchronized boolean hasValidBitmap() {
    Bitmap bitmap = getBitmap();
    return bitmap != null && !bitmap.isRecycled();
}

Manage Memory on Android 3.0 and Higher

在android3.0以及更高的版本中管理内存

 

Android 3.0 (API Level 11) introduces the BitmapFactory.Options.inBitmap field. 

If this option is set, decode methods that take the Options object will attempt to reuse an existing bitmap when loading content. 

This means that the bitmap's memory is reused, resulting in improved performance, and removing both memory allocation and de-allocation. 

There are some caveats in using inBitmap:

Android3.0(API 11)引入了BitmapFactory.Options.inBitmap

如果设置了这个选项,当加载内容的时候,使用Options对象的解码方法将会尝试复用一个存在的bitmap

这意为着bitmap的内存被复用了,导致性能提升,并且无须分配与重新分配内存

使用inBitmap有一些需要注意的地方:

 

 

The reused bitmap must be of the same size as the source content (to make sure that the same amount of memory is used), and in JPEG or PNG format (whether as a resource or as a stream).

重用的bitmap必须与源内容尺寸一致(保证相同的内存被使用),并且是JPEG或者PNG格式(作为resource或者stream)

 

The configuration of the reused bitmap overrides the setting of inPreferredConfig, if set.

You should always use the returned bitmap of the decode method, because you can't assume that reusing the bitmap worked (for example, if there is a size mismatch).

Save a bitmap for later use

如果设置了inPreferredConfig,重用的bitmap的配置就重写了inPreferredConfig

你应该总数使用解码函数返回的bitmap,因为你不能假定重用的bitmap能工作(例如,如果尺寸不匹配)

为之后使用保存一个bitmap

 

The following snippet demonstrates how an existing bitmap is stored for possible later use in the sample app. 

When an app is running on Android 3.0 or higher and a bitmap is evicted from the LruCache, a soft reference to the bitmap is placed in a HashSet, for possible reuse later with inBitmap:

下面的代码片断示范在样本应用中,一个存在的图片如何为之后可能的使用而存储

当一个应用运行在andoid3.0或者更高版本中,并且LruCache已经回收了bitmap,为了之后使用inBitmap重用bitmap,在HashSet中存放bitmap的一个软引用。

HashSet<SoftReference<Bitmap>> mReusableBitmaps;
private LruCache<String, BitmapDrawable> mMemoryCache;
 
// If you're running on Honeycomb or newer, create
// a HashSet of references to reusable bitmaps.
if (Utils.hasHoneycomb()) {
    mReusableBitmaps = new HashSet<SoftReference<Bitmap>>();
}
 
mMemoryCache = new LruCache<String, BitmapDrawable>(mCacheParams.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.
                mReusableBitmaps.add
                        (new SoftReference<Bitmap>(oldValue.getBitmap()));
            }
        }
    }
....
}

Use an existing bitmap

使用已经存在的bitmap

In the running app, decoder methods check to see if there is an existing bitmap they can use. 

For example:

在运行中的应用中,解码方法检查是否有已经存在的bitmap可供使用

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);
}

The next snippet shows the addInBitmapOptions() method that is called in the above snippet. 

It looks for an existing bitmap to set as the value for inBitmap. 

Note that this method only sets a value for inBitmap if it finds a suitable match (your code should never assume that a match will be found):

下面的代码片断展示上面代码中调用的addInBitmapOptions()方法

它寻找一个存在的bitmap作为inBitmap的值

注意,这个方法只设置inBitmap,如果找到了合适的匹配的话(你的代码不该假设这个匹配一定会找到

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 (mReusableBitmaps != null && !mReusableBitmaps.isEmpty()) {
        final Iterator<SoftReference<Bitmap>> iterator
                = mReusableBitmaps.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;
}

Finally, this method determines whether a candidate bitmap satisfies the size criteria to be used for inBitmap:

最后,这个方法决定一个备选bitmap是否满足设置inBitmap的尺寸标准

private static boolean canUseForInBitmap(
        Bitmap candidate, BitmapFactory.Options targetOptions) {
    int width = targetOptions.outWidth / targetOptions.inSampleSize;
    int height = targetOptions.outHeight / targetOptions.inSampleSize;
 
    // Returns true if "candidate" can be used for inBitmap re-use with
    // "targetOptions".
    return candidate.getWidth() == width && candidate.getHeight() == height;
}

 

原文地址如下,英文水平实在有限,希望拍砖同时能给予指正。

http://developer.android.com/training/displaying-bitmaps/manage-memory.html

 

 

转贴请保留以下链接

本人blog地址

http://su1216.iteye.com/

http://blog.csdn.net/su1216/

2
2
分享到:
评论

相关推荐

    RoaringBitmap-0.5.11-API文档-中文版.zip

    包含翻译后的API文档:RoaringBitmap-0.5.11-javadoc-API文档-中文(简体)版.zip; Maven坐标:org.roaringbitmap:RoaringBitmap:0.5.11; 标签:roaringbitmap、RoaringBitmap、jar包、java、中文文档; 使用方法:...

    RoaringBitmap-0.5.11-API文档-中英对照版.zip

    包含翻译后的API文档:RoaringBitmap-0.5.11-javadoc-API文档-中文(简体)-英语-对照版.zip; Maven坐标:org.roaringbitmap:RoaringBitmap:0.5.11; 标签:roaringbitmap、RoaringBitmap、jar包、java、API文档、...

    RoaringBitmap-0.7.45-API文档-中英对照版.zip

    包含翻译后的API文档:RoaringBitmap-0.7.45-javadoc-API文档-中文(简体)-英语-对照版.zip; Maven坐标:org.roaringbitmap:RoaringBitmap:0.7.45; 标签:roaringbitmap、RoaringBitmap、中英对照文档、jar包、java...

    RoaringBitmap-0.7.45-API文档-中文版.zip

    包含翻译后的API文档:RoaringBitmap-0.7.45-javadoc-API文档-中文(简体)版.zip; Maven坐标:org.roaringbitmap:RoaringBitmap:0.7.45; 标签:roaringbitmap、RoaringBitmap、中文文档、jar包、java; 使用方法:...

    Android下利用Bitmap切割图片

    在Android开发中,Bitmap是处理图像的基本类,用于在内存中表示位图图像。当我们需要对图片进行裁剪、缩放或进行其他操作时,Bitmap提供了丰富的功能。本篇文章将详细探讨如何在Android环境下利用Bitmap来切割图片。...

    Android代码-Android-BitmapCache

    This project came about as part of my blog post: http://www.senab.co.uk/2012/07/01/android-bitmap-caching-revisited/ Android-BitmapCache is a specialised cache, for use with Android Bitmap objects. I...

    处理bitmap内存溢出问题

    在Android开发中,处理`Bitmap`内存溢出问题是一个常见的挑战,尤其是在处理高分辨率或大尺寸图片时。当应用程序尝试加载或操作一张超出虚拟机内存预算的`Bitmap`时,系统会抛出`java.lang.OutOfMemoryError: bitmap...

    ANDROIDBITMAP内存限制OOM,OUTOFMEMORY.pdf

    1. Android内存管理:Android应用程序运行在一个受限的内存环境中,每个应用都有一个由Dalvik虚拟机管理的内存预算。当应用尝试分配的内存超过这个预算时,就会触发OutOfMemoryError。 2. OutOfMemoryError:这是一...

    Android--开发--【eoeAndroid--开发--特刊】第15期:Android--开发--多媒体.rar

    在Android平台上,多媒体开发是构建丰富用户体验的关键组成部分。Android系统为开发者提供了强大的API,支持音频、视频、图像处理以及相机功能。以下是对Android多媒体开发的详细介绍: 1. **多媒体文件支持**:...

    Android Bitmap 处理示例

    在Android开发中,Bitmap是用于表示图像数据的核心类,它在UI显示和图像处理中扮演着重要角色。然而,由于Bitmap对象通常占用大量的内存,不当的处理可能导致内存溢出(Out Of Memory)问题,因此对Bitmap进行高效...

    bitmap内存管理

    在Android开发中,Bitmap对象是用于处理图像的重要类,它涉及到内存管理和性能优化。Bitmap内存管理是Android开发者必须深入理解的一个关键领域,因为不当的Bitmap处理可能会导致内存泄漏,进而影响应用的性能和稳定...

    Android图片Bitmap和字符串String之间的相互转换

    在Android开发中,处理图像数据是一项常见的任务,而Bitmap和String是两个核心的数据类型,分别代表位图图像和文本字符串。Bitmap对象用于存储和显示图像,而String则常用于保存和传输文本信息。本篇文章将深入探讨...

    Android--开发--BitmapFunc.rar

    BitmapFunc 是一个与Android应用程序开发相关的主题,特别聚焦在Bitmap对象的使用和处理。Bitmap是Android平台中用于存储和操作图像的基本类,它在UI设计、图像加载、图像处理等场景中扮演着重要角色。本压缩包可能...

    bitmapfont-for-ugui

    - `bitmapfont-for-ugui-master.sln`:Visual Studio解决方案文件,用于开发相关的C#脚本。 - `bitmapfont-for-ugui-master.userprefs`:Unity的用户配置文件,保存了开发者特定的设置。 - `Assets`、`Project...

    android中对Bitmap图片设置任意角为圆角

    在Android开发中,Bitmap是用于表示图像数据的基本对象,它是一种内存中的图片表示形式。而当我们需要在应用程序中展示带有圆角的图片时,通常会用到Bitmap的处理技巧。本篇文章将深入探讨如何在Android中对Bitmap...

    Android应用源码之(Bitmap位图渲染与操作).zip

    在Android应用开发中,Bitmap是用于处理图像的基本类,它代表了一个位图图像。位图渲染与操作是Android图形处理的重要部分,对于优化性能、创建动态效果和自定义UI至关重要。以下将详细讨论Bitmap的使用、渲染过程...

    Android中将Bitmap转换成单色的Bmp图片

    Android不支持将Bitmap转换成单色的Bmp图片,所以参考Bmp格式说明,自己写了一个转换类。亲测有效!!!

    Android-使用Matrix对Bitmap进行处理

    在Android开发中,Bitmap是用于图像处理的基本对象,它存储并表示了图像的数据。而Matrix则是Android图形系统中的一个关键类,它允许我们对图像进行各种变换操作,如旋转、缩放、平移和倾斜等。这个教程将深入探讨...

    Android Drawable Bitmap 相互转换

    在Android开发中,Drawable和Bitmap是两种常用的图像资源类型,它们各有特点且在不同场景下有不同的优势。了解和掌握它们之间的相互转换对于优化性能和提高用户体验至关重要。本篇将详细介绍如何在Android中进行...

Global site tag (gtag.js) - Google Analytics