• 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

  • 相关阅读:
    Docker build Dockerfile 构建镜像
    Docker 容器启动 查看容器状态
    Docker 获取镜像
    Docker 容器状态查看
    windows 检测进程pid
    bzoj 1083 最小生成树
    bzoj 2039 最小割模型
    bzoj 2749 杂题
    bzoj 2748 DP
    bzoj 3190 维护栈
  • 原文地址:https://www.cnblogs.com/ghj1976/p/2788312.html
Copyright © 2020-2023  润新知