Android StrictMode and dump heaps

When Android StrictMode detects a violation of a missing object (e.g. activity), it would be helpful if I could grab a bunch of heaps at that point in time. However, there is no obvious way to configure it for this. Does anyone know a trick that you can use to achieve it, for example. a way to convince the system to run a particular piece of code just before the death penalty? I don't think StrictMode throws an exception, so I can't use the trick described here: Is there a way for the Android process to dump a bunch of heaps on OutOfMemoryError?

+5
android strictmode
Mar 08 '13 at
source share
1 answer

No exception, but StrictMode displays a message on System.err just before it completes. So, this is a hack, but it works, and since it will only be included in debug builds, I believe that this is normal ... :)

in onCreate() :

 //monitor System.err for messages that indicate the process is about to be killed by //StrictMode and cause a heap dump when one is caught System.setErr (new HProfDumpingStderrPrintStream (System.err)); 

and the class referenced by:

 private static class HProfDumpingStderrPrintStream extends PrintStream { public HProfDumpingStderrPrintStream (OutputStream destination) { super (destination); } @Override public synchronized void println (String str) { super.println (str); if (str.equals ("StrictMode VmPolicy violation with POLICY_DEATH; shutting down.")) { // StrictMode is about to terminate us... don't let it! super.println ("Trapped StrictMode shutdown notice: logging heap data"); try { android.os.Debug.dumpHprofData(app.getDir ("hprof", MODE_WORLD_READABLE) + "/strictmode-death-penalty.hprof"); } catch (Exception e) { e.printStackTrace(); } } } } 

(where app is a static field in an external class containing a link to the application context, for the convenience of links)

The line in which it matches remained unchanged from the release of gingerbread until the jelly bean, but could theoretically change in future versions, so it’s worth checking out new releases so that they still use the same message.

+7
Mar 08 '13 at 20:37
source share



All Articles