• Android 内存泄漏优化汇总


    android内存泄漏优化摘要 博客分类: android
    android内存溢出OutOfMemoryError .
    android移动应用程序的内存分配一般是8凯瑟琳约,不正确地假定处理内存处理非常easy创建OutOfMemoryError。我们的产品是最常见的错误是OutOfMemoryError的异常,
    在解决这个异常时在网上发现非常多关于OutOfMemoryError的原因的介绍。
    OutOfMemoryError主要由下面几种情况造成:
    1.数据库的cursor没有关闭。  
    操作Sqlite数据库时,Cursor是数据库表中每一行的集合,Cursor提供了非常多方法,能够非常方便的读取数据库中的值,
        能够依据索引。列名等获取数据库中的值,通过游标的方式能够调用moveToNext()移到下一行
        当我们操作完数据库后。一定要记得调用Cursor对象的close()来关闭游标,释放资源。


    2.构造adapter没有使用缓存contentview。


        在继承BaseAdapter时会让我们重写getView(int position, View   convertView, ViewGroup parent)方法。
        第二个參数convertView就是我们要用到的重用的对象

    Java代码  
    1.@Override  
    2.public View getView(int position, View convertView, ViewGroup parent) {   
    3.    ViewHolder vHolder = null;   
    4.               //假设convertView对象为空则创建新对象,不为空则复用   
    5.    if (convertView == null) {   
    6.        convertView = inflater.inflate(..., null);   
    7.        // 创建 ViewHodler 对象   
    8.        vHolder = new ViewHolder();   
    9.        vHolder.img= (ImageView) convertView.findViewById(...);   
    10.        vHolder.tv= (TextView) convertView   
    11.                .findViewById(...);   
    12.        // 将ViewHodler保存到Tag中   
    13.        convertView.setTag(vHolder);   
    14.    } else {   
    15.                       //当convertView不为空时,通过getTag()得到View   
    16.        vHolder = (ViewHolder) convertView.getTag();   
    17.    }   
    18.    // 给对象赋值。改动显示的值   
    19.    vHolder.img.setImageBitmap(...);   
    20.    vHolder.tv.setText(...);   
    21.    return convertView;   
    22.}   
    23.       //将显示的View 包装成类   
    24.static class ViewHolder {   
    25.    TextView tv;   
    26.    ImageView img;   
    27.}  
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder vHolder = null;
                    //假设convertView对象为空则创建新对象,不为空则复用
            if (convertView == null) {
                convertView = inflater.inflate(..., null);
                // 创建 ViewHodler 对象
                vHolder = new ViewHolder();
                vHolder.img= (ImageView) convertView.findViewById(...);
                vHolder.tv= (TextView) convertView
                        .findViewById(...);
                // 将ViewHodler保存到Tag中
                convertView.setTag(vHolder);
            } else {
                            //当convertView不为空时,通过getTag()得到View
                vHolder = (ViewHolder) convertView.getTag();
            }
            // 给对象赋值,改动显示的值
            vHolder.img.setImageBitmap(...);
            vHolder.tv.setText(...);
            return convertView;
        }
            //将显示的View 包装成类
        static class ViewHolder {
            TextView tv;
            ImageView img;
        }
        这里仅仅讲用法,详细性能測试文章请见:
        ListView中getView的原理+怎样在ListView中放置多个item
        http://www.cnblogs.com/xiaowenji/archive/2010/12/08/1900579.html
        Android开发之ListView适配器(Adapter)优化
        http://shinfocom.iteye.com/blog/1231511
    3.调用registerReceiver()后未调用unregisterReceiver().
         广播接收者(BroadcastReceiver)常常在应用中用到。能够在多线程任务完毕后发送广播通知UI更新,也能够接收系统广播实现一些功能
         能够通过代码的方式注冊:
        IntentFilter postFilter = new IntentFilter();
        postFilter.addAction(getPackageName() + ".background.job");
        this.registerReceiver(receiver, postFilter);
        当我们Activity中使用了registerReceiver()方法注冊了BroadcastReceiver。一定要在Activity的生命周期内调用unregisterReceiver()方法取消注冊
        也就是说registerReceiver()和unregisterReceiver()方法一定要成对出现,通常我们能够重写Activity的onDestory()方法:

    Java代码  
    1.@Override  
    2.protected void onDestroy() {   
    3.      this.unregisterReceiver(receiver);   
    4.      super.onDestroy();   
    5.}  
        @Override
        protected void onDestroy() {
              this.unregisterReceiver(receiver);
              super.onDestroy();
        }
    4.未关闭InputStream/OutputStream。
        这个就不多说了,我们操作完输入输出流都要关闭流
    5.Bitmap使用后未调用recycle()。


        图片处理不好是造成内存溢出的又一个头号原因,(在我们的产品中也有体现),

        当我们处理完图片之后能够通过调用recycle()方法来回收图片对象


    Java代码  
    1.if(!bitmap.isRecycled())   
    2.{   
    3.    bitmap.recycle()   
    4.}          
            if(!bitmap.isRecycled())
            {
                bitmap.recycle()
            }        

        除此之外:
        直接使用ImageView显示bitmap会占用较多资源。特别是图片较大的时候,可能导致崩溃。
        使用BitmapFactory.Options设置inSampleSize, 这样做能够降低对系统资源的要求。
        属性值inSampleSize表示缩略图大小为原始图片大小的几分之中的一个,即假设这个值为2,则取出的缩略图的宽和高都是原始图片的1/2,图片大小就为原始大小的1/4。
            BitmapFactory.Options bitmapFactoryOptions = new BitmapFactory.Options();  
            bitmapFactoryOptions.inJustDecodeBounds = true;  
            bitmapFactoryOptions.inSampleSize = 2;  
            // 这里一定要将其设置回false,由于之前我们将其设置成了true  
            // 设置inJustDecodeBounds为true后,decodeFile并不分配空间,即。BitmapFactory解码出来的Bitmap为Null,但可计算出原始图片的长度和宽度  
            options.inJustDecodeBounds = false;
            Bitmap bmp = BitmapFactory.decodeFile(sourceBitmap, options);  
    6.Context泄漏。


        这是一个非常隐晦的OutOfMemoryError的情况。先看一个Android官网提供的样例:

    Java代码  
    1.private static Drawable sBackground;   
    2.@Override  
    3.protected void onCreate(Bundle state) {   
    4.  super.onCreate(state);   
    5.  
    6.  TextView label = new TextView(this);   
    7.  label.setText("Leaks are bad");   
    8.  
    9.  if (sBackground == null) {   
    10.    sBackground = getDrawable(R.drawable.large_bitmap);   
    11.  }   
    12.  label.setBackgroundDrawable(sBackground);   
    13.  
    14.  setContentView(label);   
    15.}  
    private static Drawable sBackground;
    @Override
    protected void onCreate(Bundle state) {
      super.onCreate(state);

      TextView label = new TextView(this);
      label.setText("Leaks are bad");

      if (sBackground == null) {
        sBackground = getDrawable(R.drawable.large_bitmap);
      }
      label.setBackgroundDrawable(sBackground);

      setContentView(label);
    }

        这段代码效率非常快,但同一时候又是极其错误的。
        在第一次屏幕方向切换时它泄露了一開始创建的Activity。当一个Drawable附加到一个 View上时,
        View会将其作为一个callback设定到Drawable上。

    上述的代码片段。意味着Drawable拥有一个TextView的引用,
        而TextView又拥有Activity(Context类型)的引用。换句话说,Drawable拥有了很多其它的对象引用。即使Activity被 销毁,内存仍然不会被释放。
        另外,对Context的引用超过它本身的生命周期,也会导致Context泄漏。所以尽量使用Application这样的Context类型。
        这样的Context拥有和应用程序一样长的生命周期,而且不依赖Activity的生命周期。

    假设你打算保存一个长时间的对象,
        而且其须要一个 Context,记得使用Application对象。你能够通过调用Context.getApplicationContext()或 Activity.getApplication()轻松得到Application对象。
        近期遇到一种情况引起了Context泄漏,就是在Activity销毁时,里面有其它线程没有停。
        总结一下避免Context泄漏应该注意的问题:
        1.使用Application这样的Context类型。


        2.注意对Context的引用不要超过它本身的生命周期。
        3.谨慎的使用“static”keyword。
        4.Context里假设有线程。一定要在onDestroy()里及时停掉。


    7.statickeyword
        当类成员变量声明为static后,它属于类而不是属于对象。假设我们将非常大的资源对象(Bitmap。context等待)声明static。那么这些资源不会被回收的回收目标。
        它会一直存在。因此,使用statickeyword成员变量定义时要小心。

  • 相关阅读:
    查看CLOUD系统级IIS日志
    采购订单设置采购部门为缺省值
    单据头数据复制到单据体
    CLOUD设置过滤方案不共享
    BZOJ 4773: 负环 倍增Floyd
    LOJ #539. 「LibreOJ NOIP Round #1」旅游路线 倍增floyd + 思维
    BZOJ 4821: [Sdoi2017]相关分析 线段树 + 卡精
    一些常用公式/技巧
    BZOJ 4517: [Sdoi2016]排列计数 错排 + 组合
    BZOJ 3162: 独钓寒江雪 树的同构 + 组合 + 计数
  • 原文地址:https://www.cnblogs.com/hrhguanli/p/4561642.html
Copyright © 2020-2023  润新知