安卓StrictMode 和堆转储

6
当Android的StrictMode检测到泄漏对象(例如活动)违规时,如果我能在那个时刻捕获堆转储,那将非常有帮助。然而,似乎没有明显的方法来配置它以执行此操作。是否有人知道一些技巧可以用来实现这一点,例如说服系统在调用死刑之前运行特定的代码?我不认为StrictMode会抛出异常,因此我无法使用此处描述的技巧:有没有一种方法让Android进程在OutOfMemoryError时生成堆转储?

问题已经修复。您可以参考 https://issuetracker.google.com/issues/167533582。 - Prags
1个回答

9
没有异常,但是 StrictMode 会在终止前向 System.err 打印一条消息。因此,虽然这是一个 hack,但它能够发挥作用,而且只有在调试版本中才会启用,我认为这没问题... :)
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));

还有所指的类:

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();
            }
        }
    }
}

(其中app是包含对应用程序上下文引用的外部类中的静态字段,便于引用)

它匹配的字符串从gingerbread版本一直保留到jelly bean版,并且理论上它可能会在未来版本中发生变化,因此检查新版本以确保它们仍然使用相同的消息是值得的。


嗨,在我的应用程序中,我遇到了同样的问题,我尝试了你的代码,但是什么是app?我的意思是这一行:android.os.Debug.dumpHprofData(app.getDir(“hprof”,MODE_WORLD_READABLE)+“/strictmode-death-penalty.hprof”); - Zafar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接