Jul*_*les 5 android android-strictmode
当Android的StrictMode检测到泄露的对象(例如活动)违规时,如果我能够在那个时刻捕获堆转储将会很有帮助.但是,没有明显的方法来配置它来执行此操作.有没有人知道可以用来实现它的一些技巧,例如说服系统在死刑被调用之前运行一段特定代码的方法?我不认为StrictMode会抛出异常,所以我不能使用这里描述的技巧:有没有办法让Android进程在OutOfMemoryError上产生堆转储?
没有例外,但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));
Run Code Online (Sandbox Code Playgroud)
和班级提到:
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();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
(app为了便于参考,外部类中的静态字段包含对应用程序上下文的引用)
它匹配的字符串从姜饼释放一直到果冻豆都没有变化,但理论上它在未来的版本中会发生变化,因此值得检查新版本以确保它们仍然使用相同的消息.