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 ...
随机推荐
- 如果后台用framset框架布局,session过期,整个跳出回 登录页面的方法
如果session过期了,登录页面会在framset框架的右边显示,只能用 js 来做,让整个框架跳出去: 然而,这里 js 必须要用“top”才可以,作用是让整个framset都跳转,直接用 win ...
- A-Z,a-z,0-9的unicode编码表
1.转自:https://blog.csdn.net/fedawn/article/details/7307993 A-Z 的 Unicode 字符编码表 十进制 十六进制 1.“A”的 U ...
- Android开发技巧--引用另一个工程
现在已经有了一个Android工程A.我们想扩展A的功能,但是不想在A的基础上做开发,于是新建了另外一个Android工程B,想在B中引用A. 1:把工程A做成纯Jar包,这样其他的工程就可以直接引用 ...
- 【转载】“error LNK1169: 找到一个或多个多重定义的符号”的解决方法
c++的小细节的地方 原文地址:https://blog.csdn.net/xiaosu123/article/details/5665729 问题描述如下: 有 三个源文件,A.h.B.cpp.C. ...
- 2.1-2.2 Hive 中数据库(Table、Database)基本操作
官网文档:https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL 一.create table 1.官方字段 # # C ...
- 1.SJ-SLAM-14
1.引言 SLAM:Simultaneous Localization and Mapping 同时定位与地图构建 搭载特定传感器的主体,在没有环境先验信息的情况下,于运动过程中建立环境的模型,同时估 ...
- java集合框架之HashCode
参考http://how2j.cn/k/collection/collection-hashcode/371.html List查找的低效率 假设在List中存放着无重复名称,没有顺序的2000000 ...
- ASP.NET中的几种弹出框提示基本方法
NET程序的开发过程中,常常需要和用户进行信息交互,对话框的出现将解决了这些问题,下面是本人对常用对话框使用的小结,希望对大家有所帮助 我们在.NET程序的开发过程中,常常需要和用户进行信息交互,比如 ...
- SQL——基础概念
服务器登录名:指有权限登录到某服务器的用户:如sa 服务器角色:指一组固定的服务器用户,默认有9组: 登录名一定属于某些角色,默认为public 服务器角色不容许更改 登录后也不一定有权限操作数据库 ...
- 【WIP】iOS 网络通讯
创建: 2018/06/05 网络通讯的基础 App Transport Security iOS9以后增加的功能 只允许满足Apple标准的https通信 ● 对ATS进行改动的话发布的审查时有可 ...