2013-03-08 70 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發佈一直存活到果凍豆,但它在理論上可能會在未來版本中發生變化,所以值得檢查新版本以確保它們仍然使用相同的消息。