-
除了缓存bitmap之外,你还能做其他一些事情来优化GC和bitmap的复用。推荐的策略取决于
Android的
系统版本。附件中的例子会向你展示如何设计app以便在不同的Android版本中提高app的内存性能。 在不同的Android版本中,bitmap的内存管理有所不同。 在Android2.2(api level8)和之前的版本中,当GC触发的时候,App的主线程将会停止。这会导致一个明显的卡顿,并降低用户体验。从Android2.3开始加入了并发GC,这意味着只要bitmap不再被引用,内存将会马上被回收。 在Android2.3.3(api level 10)和以前的版本中,bitmap的像素数据保存在底层内存中,而bitmap本身是保存在
虚拟机的heap中。保存在底层内存中的像素数据的回收是不可预测的,这会很容易引起App超过内存限制并且崩溃。在Android3.0以后,bitmap和关联的像素数据都保存在虚拟机的heap中。 下面将介绍在不同的Android版本中如何优化bitmap的内存。 1.在Android2.3.3和之前版本中管理内存。 在Android2.3.3和之前的版本中,推荐使用recycle()方法来管理内存。如果在App中显示很大的图片,将很有可能引起 OutOfMemoryError异常。recycle()方法允许APP尽快回收内存。需要注意的是,只能在你确定bitmap不会再被使用时才能调用recycle()方法。如果后续要显示一个已经调用过recycle()方法的bitmap,你将会得到Canvas: trying to use a recycled bitmap”异常。 以下的代码片段显示调用recycle()方法的一个例子。这里使用引用计数的方式来跟踪现在正在显示的和正在缓冲中的bitmap(变量mDisplayRefCount和mCacheRefCount)。当满足下面两个条件时将会执行图片回收。 1)mDisplayRefCount和mCacheRefCount同时为0。 2)bitmap不为null,并且没有调用过recycle()方法。
123456789101112131415161718192021222324252627282930313233343536373839404142434445
private
int
mCacheRefCount =
0
;
private
int
mDisplayRefCount =
0
;
...
// drawable的显示状态发生改变.
// 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();
}
1234567891011121314151617181920212223242526272829303132Set<softreference<bitmap>> mReusableBitmaps;
private
LruCache<string, bitmapdrawable=
""
> mMemoryCache;
// If you're running on Honeycomb or newer, create a
// synchronized HashSet of references to reusable bitmaps.
if
(Utils.hasHoneycomb()) {
mReusableBitmaps =
Collections.synchronizedSet(
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()));
}
}
}
....
}</bitmap></string,></softreference<bitmap></string,></softreference<bitmap>
123456789101112131415public
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()方法具体实现如下所示。它用来寻找一个已存在的bitmap用来设置 inBitmap字段。要注意该方法如果找到合适的bitmap只会设置 inBitmap字段(你的代码不应该假定总是能寻找到匹配)。1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950private
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()) {
synchronized
(mReusableBitmaps) {
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;
}</softreference<bitmap>
12345678910111213141516171819202122232425262728293031323334static
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 = targetOptions.outWidth / targetOptions.inSampleSize;
int
height = targetOptions.outHeight / 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
;
}
bitmap优化策略
最新推荐文章于 2024-09-21 14:23:15 发布