Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Dump the heap on OutOfMemoryError crashes in your debug builds.
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;
}
}
@gordonpro

This comment has been minimized.

Copy link

commented May 11, 2015

A good manner.

@xxxzhi

This comment has been minimized.

Copy link

commented Sep 4, 2015

Nice

@fyhack

This comment has been minimized.

Copy link

commented Dec 16, 2015

+1

@wonghoman

This comment has been minimized.

Copy link

commented Jan 16, 2016

Thanks for share.

@chenshengfa1990

This comment has been minimized.

Copy link

commented Mar 23, 2016

Thanks

@yadav-rahul

This comment has been minimized.

Copy link

commented Jan 8, 2017

+1

@Ankur008

This comment has been minimized.

Copy link

commented Feb 1, 2017

hey can anyone explain me how to use this code. As I am facing OOM error continuously (reported by leaks canary lib). How to use above code to dump file. I think FILENAME means heap dump file name, how can I get it, where it is stored. I will get it using Leaks app after clicking on OOM error. But how will I get it from my app.

@MagicMashRoom

This comment has been minimized.

Copy link

commented Aug 14, 2017

ths good code

@mobileappconsultant

This comment has been minimized.

Copy link

commented Nov 8, 2018

Try OomExceptionHandler.install(yourContext);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.