zoukankan      html  css  js  c++  java
  • Android大图片内存清理

    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

  • 相关阅读:
    小白学习React官方文档看不懂怎么办?1.起步
    部分安卓机调用相册跟相机出问题了
    var与let与const
    小白学习React官方文档看不懂怎么办?3.元素渲染
    小白学习React官方文档看不懂怎么办?2.JSX语法
    jQuery简单面试题
    HTML页面插入图片,使用background还是img标签
    HTML规范
    img标签不能直接作为body的子元素
    java 学习第三天小练习
  • 原文地址:https://www.cnblogs.com/ghj1976/p/2788312.html
Copyright © 2011-2022 走看看