在2.3.3及以下版本:

通過定義兩個整形變量來檢測bitmap是否display過或者已經在緩存中

下面的代碼當bitmap滿足兩個條件就被回收掉:

1. 兩個整形變量都變為0

2. 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();
}

Android3.0以上版本内存管理

BitmapFactory.Options.inBitmap:解码器将尝试重用已经存在的位图对象:

4.4之前有以下要求

•被重用的位图对象必须与源内容大小一致,并且是JPEG或PNG格式

•inSampleSize 必須設置成 1

•被重用的位图的configuration将覆盖inPreferredConfig设置,如果有的话

•你应该使用解码方法返回的位图对象。被重用的位图不一定还能用

Set<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()));
}
}
}
....
}

Decode方法检查是否有现存的位图可用:

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);
} 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()) {
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;
} 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 = 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;
}

Android Training精要(七)内存管理的更多相关文章

  1. Android Training精要(六)如何防止Bitmap对象出现OOM

    1.使用AsyncTask異步加載bitmap圖片避免OOM: class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> ...

  2. 每个Android开发者必须知道的内存管理知识

    原文:每个Android开发者必须知道的内存管理知识 拷贝在此处,以备后续查看. 相信一步步走过来的Android从业者,每个人都会遇到OOM的情况.如何避免和防范OOM的出现,对于每一个程序员来说确 ...

  3. Android Training精要(二)開啟ActionBar的Overlay模式

    在3.0上的實現 <resources> <!-- the theme applied to the application or activity --> <style ...

  4. Android Training精要(一)ActionBar上级菜单导航图标

    Navigation Up(ActionBar中的上级菜单导航图标) 在android 4.0中,我们需要自己维护activity之间的父子关系. 导航图标ID为android.R.id.home @ ...

  5. 【Android手机测试】linux内存管理 -- 一个进程占多少内存?四种计算方法:VSS/RSS/PSS/USS

    在Linux里面,一个进程占用的内存有不同种说法,可以是VSS/RSS/PSS/USS四种形式,这四种形式首字母分别是Virtual/Resident/Proportional/Unique的意思. ...

  6. Android Training精要(五)讀取Bitmap對象實際的尺寸和類型

    讀取Bitmap對象實際的尺寸和類型 BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecode ...

  7. Android Training精要(四) Intent注意事项

    判断有处理Intent的Activity PackageManager packageManager = getPackageManager(); List<ResolveInfo> ac ...

  8. Android Training精要(三)不同分辨率图片缩放倍数

    各DPI图片倍率 xhdpi: 2.0 hdpi: 1.5 mdpi: 1.0 (baseline) ldpi: 0.75 这就意味着如果有一张xhdpi下200*200的图片, 你应该提供同样的图片 ...

  9. Android Training - 管理应用的内存

    http://hukai.me/android-training-managing_your_app_memory/ Random Access Memory(RAM)在任何软件开发环境中都是一个很宝 ...

随机推荐

  1. zoj2432 hdoj1423 最长公共上升子序列(LCIS)

    zoj2431  http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=2432 hdoj 1423 http://acm.hdu. ...

  2. Android画廊控件之Gallery

    Gallery:用来显示图片列表.可以左右拖动. 如图: 图片取自http://www.cnblogs.com/menlsh/archive/2013/02/26/2934434.html 在Gall ...

  3. MarkDown Pad2的一些用法

    一.标题 1.使用命令Ctrl+1 标题一 2.使用文字回车后,加上"-"号,再回车.就有如下的示例: 标题二 注意:减(-)号是用于最近的那一行文字变成标题. 二.背景 例如我要 ...

  4. oracle 定义临时表

    创建Oracle 临时表,可以有两种类型的临时表: 会话级的临时表 事务级的临时表 . 1) 会话级的临时表因为这这个临时表中的数据和你的当前会话有关系, 当你当前SESSION不退出的情况下,临时表 ...

  5. (五)Hibernate 操作对象

    所有项目导入对应的hibernate的jar包.mysql的jar包和添加每次都需要用到的HibernateUtil.java 第一节:Hibernate 中四种对象状态 临时状态(transient ...

  6. HDU 3008 Warcraft(DP)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3008 题目大意:人有100血和100魔法,每秒增加 t 魔法(不能超过100).n个技能,每个技能消耗 ...

  7. bzoj1231: [Usaco2008 Nov]mixup2 混乱的奶牛

    思路:状压dp,设f[i][j]表示当前已经选出的牛的状态为i,最后一头选出的牛为j的方案数. 然后注意就是初值不能是f[0][i]=1,因为所有牛本来都可以第一个被选中,然而这样一定初值有些牛可能就 ...

  8. (转)linux多线程,线程的分离与结合

    转自:http://www.cnblogs.com/mydomain/archive/2011/08/14/2138454.htm 线程的分离与结合     在任何一个时间点上,线程是可结合的(joi ...

  9. 九度OJ 1371 最小的K个数 -- 堆排序

    题目地址:http://ac.jobdu.com/problem.php?pid=1371 题目描述: 输入n个整数,找出其中最小的K个数.例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4 ...

  10. Struts2配置文件_常量属性_独立测试分析

    <constant name="struts.devMode" value="true" /> 设置开发模式,可以了解详细信息,该属性指定视图标签默 ...