Created
May 6, 2015 17:18
-
-
Save pyricau/4726389fd64f3b7c6f32 to your computer and use it in GitHub Desktop.
Dump the heap on OutOfMemoryError crashes in your debug builds.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Context; | |
import android.os.Debug; | |
import java.io.File; | |
public class OomExceptionHandler implements Thread.UncaughtExceptionHandler { | |
private static final String FILENAME = "out-of-memory.hprof"; | |
public static void install(Context context) { | |
Thread.UncaughtExceptionHandler defaultHandler = Thread.getDefaultUncaughtExceptionHandler(); | |
if (defaultHandler instanceof OomExceptionHandler) { | |
return; | |
} | |
OomExceptionHandler oomHandler = new OomExceptionHandler(defaultHandler, context); | |
Thread.setDefaultUncaughtExceptionHandler(oomHandler); | |
} | |
private final Thread.UncaughtExceptionHandler defaultHandler; | |
private final Context context; | |
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 (Throwable ignored) { | |
} | |
} | |
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; | |
} | |
} |
Try OomExceptionHandler.install(yourContext);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ths good code