Android默认内部加载图片是以ARGB_8888格式的位图来加载所有图像的,这就意味着,每一个像素需要用4个字节来表述。例如,一个800*400像素的图像需要800*400*4=1536000字节,大约1.5MB。
一个1280 × 712 像素的图像,需要1280*712*4=3545440字节=3.56MB。
性能考虑,android为了提高效率,Bitmap真正的位图数据是在ndk中用c写的。所以用setCallback是不能销毁位图数据的,应该调用Bitmap的recycle()来清理内存。
Layout布局文件中定义的背景,Android默认是缓存并没有销毁的。
所以需要能销毁内存中的背景图,需要做如下处理。
布局文件
注意这里定义了id,同时没有用android:background定义背景
<?xmlversion="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rootView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<!-- android:background="@drawable/splash" -->
</LinearLayout>
定义背景是通过下面代码定义的:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
// http://blog.csdn.net/micro_rat/article/details/6307067
LinearLayout rootView = (LinearLayout) this.findViewById(R.id.rootView);
Bitmap bm = BitmapFactory.decodeResource(this.getResources(), R.drawable.splash);
BitmapDrawable bd = new BitmapDrawable(this.getResources(), bm);
rootView.setBackgroundDrawable(bd);
}
销毁图片资源用下面代码:
@Override
protected void onDestroy() {
// http://blog.csdn.net/micro_rat/article/details/6307067
LinearLayout rootView = (LinearLayout) this.findViewById(R.id.rootView);
BitmapDrawable bd = (BitmapDrawable)rootView.getBackground();
bd.setCallback(null);
bd.getBitmap().recycle();
super.onDestroy();
}
不能用Layout上定义布局,onDestroy 销毁图片,是因为Layout布局上定义时,会自动从缓存中取数据,而我们销毁了这时候会报错误:“try to use a recycled bitmap"的异常。上面的代码书写方式才不会报错。
参考资料
关于android中使用很多大图片的一些做法
http://blog.csdn.net/micro_rat/article/details/6307067
http://stackoverflow.com/questions/10661894/xml-menu-background-memory-issues
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
2011-11-25 PHP 和 Android MD5 加密出来结果是一样的代码
2010-11-25 win7 下安装 Microsoft Web Application Stress Tool