6.3

一、内存泄漏检测与修复
使用 LeakCanary 检测 Activity 泄漏:
java
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();

    if (LeakCanary.isInAnalyzerProcess(this)) {
        // 此进程专用于LeakCanary进行堆分析。
        // 在此处不要初始化你的应用程序。
        return;
    }
    LeakCanary.install(this);
    
    // 正常的应用程序初始化
}

}

二、内存优化实践
优化 Bitmap 内存占用:
java
public class ImageUtils {
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// 首先不加载图片,仅获取图片尺寸
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);

    // 计算采样率
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    
    // 加载压缩后的图片
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}

private static int calculateInSampleSize(BitmapFactory.Options options,
                                        int reqWidth, int reqHeight) {
    // 原始图片尺寸
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;
    
    if (height > reqHeight || width > reqWidth) {
        final int halfHeight = height / 2;
        final int halfWidth = width / 2;
        
        // 计算最大采样率,使得图片高度和宽度都大于请求的高度和宽度
        while ((halfHeight / inSampleSize) >= reqHeight && 
               (halfWidth / inSampleSize) >= reqWidth) {
            inSampleSize *= 2;
        }
    }
    
    return inSampleSize;
}

public static void recycleBitmap(Bitmap bitmap) {
    if (bitmap != null && !bitmap.isRecycled()) {
        bitmap.recycle();
        bitmap = null;
    }
}

}

posted @ 2025-06-03 21:51  李蕊lr  阅读(15)  评论(0)    收藏  举报