android 内存泄漏篇——OOM问题的解决办法总结

来源:互联网 发布:meego社交软件 编辑:程序博客网 时间:2024/06/11 04:09

android 内存泄漏篇——OOM问题的解决办法总结

首先先介绍几个概念:

1:强引用:拥有声明的引用,jvm宁愿抛出OOM(内存溢出)都不会进行 GC回收的声明类型;
2:软引用:SoftReference 等 声明的引用,当jvm中内存不足时会被回收的声明类型;
3:弱引用:WeakReference 等声明的引用,当GC轮询到时会立即回收;
4:虚引用:这个不太理解

再介绍几个android 中特有的数据结构

1:LruCach:Least Recently Used (近期最少使用)算法做的缓存处理类;
2:SparseArray:性能比ArrayList要高的链表类
3:Pair:数据对:Pair pair = new Pair(first,second);pair.first();

再来两个内存检测工具

1:MAT(memery anlaze tool):内存分析工具;
2:LeakCanary:一个开源的android 内存工具(推荐)用法简单集成到自己的项目中会多一个Leak的app出现在手机中,当出现泄露时会提示具体的对象泄露

图片压缩处理

1:通过设定Options中的inSimpleSize = x 来控制读入位图大小,x一般为2的倍数,inSimpleSize = 2;代表长和宽都减少1/2得到的图片,一般不为2的倍数可能导致图片的扭曲
2:通过Bitmap中的compress 函数进行压缩大小,ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,100,outputStream;获得字节流outputStream 的图片数据

再通过 BitmapFactory.decodeByteArray(outputStream.toByteArray(),0,outputStream.size());
获得新的压缩的图片
3:获得固定大小的位图
/**
* 获取指定路径下的图片
* @param filePath 文件路径
*/
public Bitmap getLocalBitmapWithSize(String filePath,int inSampleSize){
BitmapFactory.Options param = new BitmapFactory.Options();
param.inPreferredConfig = Bitmap.Config.ARGB_8888;
param.inSampleSize = inSampleSize;
// 获取位图参数
BitmapFactory.decodeFile(filePath,param);
SoftReference bitmapReference = new SoftReference(BitmapFactory.decodeFile(filePath,param));//加入内存中
param = null;
return bitmapReference.get();
}
/**
*压缩图片到指定大小,返回结果有误差
* @param bitmap 原图片数据
* @param maxSize 最大限制 单位(KB)
* @return 处理后的图片数据
*/
public Bitmap compressBitmap(Bitmap bitmap, int maxSize){
BitmapFactory.Options param = new BitmapFactory.Options();
param.inJustDecodeBounds = true;
param.inPreferredConfig = Bitmap.Config.ARGB_8888;

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();    bitmap.compress(Bitmap.CompressFormat.JPEG,100,outputStream);    BitmapFactory.decodeByteArray(outputStream.toByteArray(),0,outputStream.size());    int orignSize = outputStream.toByteArray().length / 1024;//单位为kb    int scale = orignSize / maxSize; //缩放比率    if (scale <= 1){// 如果原图小于限定大小,则不压缩        return bitmap;    }    double bitmapWidth =  bitmap.getWidth();    double bitmapHeight = bitmap.getHeight();    double newBitmapWidth = bitmapWidth / Math.sqrt(scale);    double newBitmapHeight = bitmapHeight / Math.sqrt(scale);    float scaleWidth =(float) (newBitmapWidth / bitmapWidth);    float scaleHeight = (float) (newBitmapHeight / bitmapHeight);    Matrix matrix = new Matrix();    matrix.postScale(scaleWidth,scaleHeight);    SoftReference<Bitmap> bitmapSoftReference = new SoftReference<Bitmap>(            Bitmap.createBitmap(bitmap,0,0,(int)bitmapWidth,(int)bitmapHeight,matrix,true));    bitmap.recycle();    param = null;    outputStream = null;    return bitmapSoftReference.get();}

总结

说了那么多概念的东西,其实我觉得android 里面只要明白了这些概念,oom问题就迎刃而解了;1:使用android 特有的数据结构能够提高性能2:使用软引用或者Lrucahe处理图片,读取图片显示,尽量处理成缩略图显示3:最重要的就是使用mat和LeakCanary进行内存泄漏检测,将泄露的内存引用赋值为null,Gc便可以对泄露的内存进行回收了
0 0
原创粉丝点击