阅读本文大概需要 7.8 分钟。
作者: 邹阿涛涛涛涛涛涛
原文: https://juejin.im/post/5d617d6851882575e8054fab
前言
背景
干掉OOM,我们干了什么?

一、排查内存泄漏
我们采用了LeakCanary,实现了一个自定义的Service继承自DisplayLeakService,重写afterDefaultHandling方法,将内存泄漏上报到Sentry。
public static class LeakReportService extends DisplayLeakService {
@SuppressWarnings("ThrowableNotThrown")
@Override
protected void afterDefaultHandling(@NonNull HeapDump heapDump, @NonNull AnalysisResult result, @NonNull String leakInfo) {
if (!result.leakFound || result.excludedLeak) {
return;
}
try {
Exception exception = new Exception("Memory Leak from LeakCanary");
exception.setStackTrace(result.leakTraceAsFakeException().getStackTrace());
Sentry.capture(exception);
} catch (Exception e) {
e.printStackTrace();
}
}
}
除了LeakCanary,我们还使用了Android Studio自带的Profiler工具对内存有进行分析,包括内存泄漏的问题和内存峰值过高的问题。
方法:找到对应的Bitmap对象,然后~ ,点击它,然后就可以preview,如下图:

二、兜底策略
private void traverse(ViewGroup root) {
final int childCount = root.getChildCount();
for (int i = ; i < childCount; ++i) {
final View child = root.getChildAt(i);
if (child instanceof ViewGroup) {
child.setBackground(null);
traverse((ViewGroup) child);
} else {
if (child != null) {
child.setBackground(null);
}
if (child instanceof ImageView) {
((ImageView) child).setImageDrawable(null);
} else if (child instanceof EditText) {
((EditText) child).cleanWatchers();
}
}
}
}
三、内存峰值太高

查Bitmap分配查出来的问题
没有传入合适的Config,绝大多数地方传的都是ARGB_8888,其实根本没必要,改成565直接少一半内存占用 用UIL进行loadImage时,没有传入targetSize,这就直接导致了UIL内部是以屏幕的尺寸去Decode的Bitmap对象,想象一下,一个特别小的头像View,持有着一个屏幕大小尺寸的Bitmap对象,这谁顶得住。 许多地方不需要存内存缓存,比如闪屏广告图,app启动之后就不会再使用了,可以加载的时候 memoryCache(false) 许多地方不需要磁盘缓存,比如发布动态,从图库中选图,不需要再存一份磁盘缓存了,本身那些图片都是本地图片。直接 diskCache(false)


public static void clearAnimationCache() {
if (frescoAnimationCache == null) {
//采用反射的方法,如果native、rn同时初始化Fresco,会造成Fresco内部存储动图的//CountingMemoryCache不是Fresco.getImagePipelineFactory().getBitmapCountingMemoryCache()了
//暂时用反射的方法,拿到存储动图缓存的cache,并清空
try {
Class imagePipelineFactoryClz = Class.forName("com.facebook.imagepipeline.core.ImagePipelineFactory");
Field mAnimatedFactoryField = imagePipelineFactoryClz.getDeclaredField("mAnimatedFactory");
mAnimatedFactoryField.setAccessible(true);
AnimatedFactoryV2Impl animatedFactoryV2 = (AnimatedFactoryV2Impl) mAnimatedFactoryField.get(Fresco.getImagePipelineFactory());
Class animatedFactoryV2ImplClz = Class.forName("com.facebook.fresco.animation.factory.AnimatedFactoryV2Impl");
Field mBackingCacheField = animatedFactoryV2ImplClz.getDeclaredField("mBackingCache");
mBackingCacheField.setAccessible(true);
frescoAnimationCache = (CountingMemoryCache) mBackingCacheField.get(animatedFactoryV2);
} catch (Exception e) {
Log.e("FrescoUtil", e.getMessage(), e);
}
}
if (frescoAnimationCache != null) {
frescoAnimationCache.clear();
}
Fresco.getImagePipelineFactory().getBitmapCountingMemoryCache().clear();
Fresco.getImagePipelineFactory().getEncodedCountingMemoryCache().clear();
}
又一个兜底方案
为了防止峰值过高,我们还起了一个线程,定时的去监控实时的内存使用情况,如果内存紧急了,直接清空UIL/Fresco的内存缓存救急
private static Handler lowMemoryMonitorHandler;
private static final int MEMORY_MONITOR_INTERVAL = 1000 * 60;
/**
* 开启低内存监测,如果低内存了,作出相应的反应
*/
public static void startMonitorLowMemory() {
HandlerThread thread = new HandlerThread("thread_monitor_low_memory");
thread.start();
lowMemoryMonitorHandler = new Handler(thread.getLooper());
lowMemoryMonitorHandler.postDelayed(releaseMemoryCacheRunner, MEMORY_MONITOR_INTERVAL);
}
/**
* 低内存时清空Fresco、UIL的内存缓存
* 如果已用内存达到了总的 80%时,就清空缓存
*/
private static Runnable releaseMemoryCacheRunner = new Runnable() {
@Override
public void run() {
long alreadyUsedSize = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
long maxSize = Runtime.getRuntime().maxMemory();
if (Double.compare(alreadyUsedSize, maxSize * 0.8) == 1) {
BitmapUtil.clearMemoryCaches();
}
lowMemoryMonitorHandler.postDelayed(releaseMemoryCacheRunner, MEMORY_MONITOR_INTERVAL);
}
};
五、特大图排查优化
六、总结
检查内存泄漏,包括常见的Context泄漏、单例泄漏、EditText的TextWatcher泄漏等等,找到并fix他们,最简单的例子,能传application的地方就不要硬传个activity过去 兜底方案:
在Activity onDestory的时候,遍历View树,清空backGround、Drawable、EditText的TextWatcher等
优化UIL的使用 memoryCache选用,不是所有的图片加载都需要UIL去塞一份内存缓存的,比如闪屏图 ImageLoader.getInstance().displayImage()的时候,传进去的Option不要无脑ARGB_8888,讲道理来说,无脑RGB_565都是没啥问题的。。 调用displayImage的时候,最好传一个ImageSize作为targetSize,这个size可以是你的ImageView的尺寸,当View尺寸本身不确定的时候,可以传一个大概值,比如我们app中有好些个的头像标准尺寸,为了偷懒,直接传MaxAvatarSize就ok Fresco的优化 RN中使用Fresco加载图片,在RN Activity销毁的时候,会将Fresco默认的memory cache清空,但是动图的缓存没有清。手动清一下。我们项目中每个RN页面都会带一个Loading动图,所以吃了大亏。。

往期精彩回顾
你还在认为 count(1) 比 count(*) 效率高?

朕已阅 
