package com.jaeger.ninegridimgdemo.entity;
import android.content.Context;
import android.os.Debug;
import java.io.File;
import java.io.IOException;
/**
* Created by 杨阳洋 on 2017/11/23.
* usg:OOM异常
*/
public class OomExceptionHandler implements Thread.UncaughtExceptionHandler {
private static final String FILENAME = "out-of-memory.hprof";
private final Thread.UncaughtExceptionHandler defaultHandler;
private final Context context;
public static void install(Context context){
Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
if(defaultUncaughtExceptionHandler instanceof OutOfMemoryError) {
return;
}
OomExceptionHandler oomHandler = new OomExceptionHandler(defaultUncaughtExceptionHandler, context);
Thread.setDefaultUncaughtExceptionHandler(oomHandler);
}
public OomExceptionHandler(Thread.UncaughtExceptionHandler defaultHandler, Context context) {
this.defaultHandler = defaultHandler;
this.context = context.getApplicationContext();
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if(containsOom(ex)) {
File heapDumpFile = new File(context.getFilesDir(), FILENAME);
try {
Debug.dumpHprofData(heapDumpFile.getAbsolutePath());
} catch (IOException e) {
}
}
defaultHandler.uncaughtException(thread, ex);
}
private boolean containsOom(Throwable ex){
if(ex instanceof OutOfMemoryError) {
return true;
}
while ((ex = ex.getCause()) != null){
if(ex instanceof OutOfMemoryError) {
return true;
}
}
return false;
}
}
内存泄漏Exception类-OomExceptionHandler
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 描述 在使用handler时,一般我们用于解决跨线程操作的问题,一般开启线程可能是处理耗时操作,因此很可能导致内存...
- Handler和内部类怎么引起内存泄漏? 先看下面一段代码: 我们平时使用Handler的时候,相信很多人都会这样...