Android StrictMode and heap dumps

2019-01-25 16:37发布

When Android's StrictMode detects a leaked object (e.g. activity) violation, it would be helpful if I could capture a heap dump at that moment in time. There's no obvious way, however, to configure it to do this. Does anyone know of some trick that can be used to achieve it, e.g. a way to convince the system to run a particular piece of code just prior to the death penalty being invoked? I don't think StrictMode throws an exception, so I can't use the trick described here: Is there a way to have an Android process produce a heap dump on an OutOfMemoryError?

1条回答
beautiful°
2楼-- · 2019-01-25 16:47

No exception, but StrictMode does print a message to System.err just before it terminates. So, this is a hack, but it works, and as it's only going to be enabled on debug builds I figure it's fine... :)

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 referred to:

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 the outer class containing a reference to the application context, for ease of reference)

The string it matches has survived unchanged from gingerbread release all the way up to jelly bean, but it could theoretically change in future versions, so it's worth checking new releases to ensure they still use the same message.

查看更多
登录 后发表回答