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的時候,相信很多人都會這樣...