Android笔记--Bitmap(三) 针对不用Android版本的位图管理
Bitmap(三) | Android不同版本的相应操作
在不同的Android版本中。位图的存储方式是不同的。
1.小于等于 Android 2.2 (API level 8)
垃圾收集器回收内存时会使所有线程停止,这回严重影响性能。Android2.3之后,加入了并行的垃圾回收。这就让不再被引用的位图可以直接被回收。
2.Android 2.3.3 (API level 10) and lower
这种版本的设备,位图的像素数据存储在native的内存中。而bitmap对象在VM的堆内存中。他和bitmap是分离的。而在native内存存储的像素数据不具有可预知性,所以桐城会导致应用内存溢出或者崩溃。
3.Android 3.0 (API level 11) through Android 7.1 (API level 25)
像素数据和bitmap都存储在VM的堆内存上。
4.Android 8.0 (API level 26), and higher,
像素数据存在native堆上
所以对于不同的版本要做不同的位图管理。
1. <= Android 2.3.3(API10)版本的位图处理
1.需要显示调用recycle()方法
private int mCacheRefCount = 0;
private int mDisplayRefCount = 0;//这两个变量负责计数
//只有当界面既没有引用位图。缓存中也没有保存位图且没有被界面展示,且bitmap还存在的时候才允许调用recycle()
...
// 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();
}
2. >= Android 3.0 (API level 11) 版本的位图管理
Android3.0以后引入了 BitmapFactory.Options.inBitmap变量。如果设置了这一项,那decodeXXX方法们在用这个Options加载位图时将尝试重用现有位图。这意味着位图的内存被重用,从而提高了性能,同时消除了内存分配和回收的过程。
但是 inBitmap得使用时有限制的,特别是在Android 4.4(API Level 19)之前,只有同等大小的位图支持重复利用
a 保存bitmap供后续使用
下面的代码片段演示了如何存储现有位图,以便以后在示例应用程序中使用。当一个应用程序在Android 3。0或更高的运行,而且位图从LruCache剔除出来了,那位图软引用被放置在一个HashSet中,预备后来inbitmap可能重用。
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()));
}
}
}
....
}
b 使用一个已经存在的位图
在解压位图的时候如果是Honeycomb或者高版本就试着使用inBitmap
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);
}
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()) {
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;
}
最后这个方法决定是否有合适的位图满足需要的大小
注意:4.4版本之后只要是可重用的位图大于等于需要的位图大小就可以重用了。所以建议针对4.4版本做这个重用操作
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笔记--Bitmap(三) 针对不用Android版本的位图管理的更多相关文章
- Android笔记(三十三) Android中线程之间的通信(五)Thread、Handle、Looper和MessageQueue
ThreadLocal 往下看之前,需要了解一下Java的ThreadLocal类,可参考博文: 解密ThreadLocal Looper.Handler和MessageQueue 我们分析一下之前的 ...
- Android笔记(三十一)Android中线程之间的通信(三)子线程给主线程发送消息
先看简单示例:点击按钮,2s之后,TextView改变内容. package cn.lixyz.handlertest; import android.app.Activity; import and ...
- Android笔记(三十) Android中线程之间的通信(二)Handler消息传递机制
什么是Handler 之前说过了,Android不允许主线程(MainThread)外的线程(WorkerThread)去修改UI组件,但是又不能把所有的更新UI的操作都放在主线程中去(会造成ANR) ...
- Android群英传笔记——第三章:Android控件架构与自定义控件讲解
Android群英传笔记--第三章:Android控件架构与自定义控件讲解 真的很久没有更新博客了,三四天了吧,搬家干嘛的,心累,事件又很紧,抽时间把第三章大致的看完了,当然,我还是有一点View的基 ...
- Android笔记(三) 使得Activity之间可以跳转---Intent
什么是Intent 一个APP肯定不单单由一个Activity构成,我们在使用过程中,经常需要在多个Activity中跳转,Android中Intent可以帮我们来完成在各个Activity中跳转的功 ...
- 【转】android 电池(三):android电池系统
关键词:android电池系统电池系统架构 uevent power_supply驱动 平台信息: 内核:linux2.6/linux3.0系统:android/android4.0 平台:S5PV3 ...
- uni-app&H5&Android混合开发三 || uni-app调用Android原生方法的三种方式
前言: 关于H5的调用Android原生方法的方式有很多,在该片文章中我主要简单介绍三种与Android原生方法交互的方式. 一.H5+方法调用android原生方法 H5+ Android开发规范官 ...
- Android笔记(三):View一些值得注意的地方
Button android:textAllCaps="false" // Button上的英文字符不转成大写 EditText android:maxLines="2& ...
- Android群英传神兵利器读书笔记——第三章:Android Studio奇技淫巧
这篇文章篇幅较长,可以使用版权声明下面的目录,找到感兴趣的进行阅读 3.1 Android Studio使用初探 Project面板 Stucture面板 Android Monitor Keymap ...
随机推荐
- bzoj 2083 [Poi2010]Intelligence test——思路+vector/链表
题目:https://www.lydsy.com/JudgeOnline/problem.php?id=2083 给每个值开一个vector.每个询问挂在其第一个值上:然后枚举给定序列,遇到一个值就访 ...
- HDU2639(01背包第K大)
Bone Collector II Time Limit: 5000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others ...
- HDU3466(01背包变种)
Proud Merchants Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/65536 K (Java/Others) ...
- CS231n 2016 通关 第五、六章 Fully-Connected Neural Nets 作业
要求:实现任意层数的NN. 每一层结构包含: 1.前向传播和反向传播函数:2.每一层计算的相关数值 cell 1 依旧是显示的初始设置 # As usual, a bit of setup impor ...
- Ubuntu install JDK
1.#下载JDK,记住保存的目录 2. sudo mkdir /usr/java 3. sudo tar zxvf jdk-7u75-linux-x64.tar.gz -C /usr/java 4. ...
- kvm详细介绍
KVM详解,太详细太深入了,经典 2016-07-18 19:56:38 分类: 虚拟化 原文地址:KVM详解,太详细太深入了,经典 作者:zzjlzx KVM 介绍(1):简介及安装 http:// ...
- java 整除(/) 求余(%) 运算
1. java 整除(/) 求余(%) 运算 1.求余 System.out.println(11%2); //顾名思义就是11除2的余数-->1 System.out. ...
- 创建Sitemap文件供搜索引擎使用
以下内容转载自 http://www.cnblogs.com/webtrados/archive/2009/12/29/1635305.html 如何创建Sitemap文件 Sitemap的格式有XM ...
- P5175 数列(矩阵加速)
//minamoto #include<bits/stdc++.h> #define R register #define ll long long #define fp(i,a,b) f ...
- jstl标签库不起作用,直接输出表达式
引用jstl.jar包 在jsp页面添加<%@ page isELIgnored="false"%>即可