2013-03-08 71 views
5

当Android的StrictMode检测到泄漏对象(例如活动)违规时,如果我可以在该时刻捕获堆转储将会很有帮助。但是,没有明显的方法来配置它来执行此操作。有谁知道可以用来实现它的一些技巧,例如一种说服系统在死刑被调用之前运行特定代码的方法?我不认为StrictMode抛出一个异常,所以我不能使用下面介绍的技巧:Is there a way to have an Android process produce a heap dump on an OutOfMemoryError?Android StrictMode和堆转储

回答

7

也不例外,但StrictMode不打印消息System.err它终止之前。所以,这是一个黑客,但它的工作原理,并为它一定会在调试启用构建我想这很好... :)

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发布一直存活到果冻豆,但它在理论上可能会在未来版本中发生变化,所以值得检查新版本以确保它们仍然使用相同的消息。