Android的StrictMode和堆转储 [英] Android StrictMode and heap dumps

查看:565
本文介绍了Android的StrictMode和堆转储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Android的StrictMode检测到泄漏的对象(即活动)侵犯,这将是有益的,如果我能及时捕获堆转储的那一刻。有没有明显的方法,但是,将其配置为做到这一点。有谁知道一些窍门可以用来实现这一目标,例如,对一个办法说服系统运行一段特定的code之前死刑被调用?我不认为StrictMode抛出一个异常,所以我不能用这里描述的伎俩:<一href="http://stackoverflow.com/questions/6131769/is-there-a-way-to-have-an-android-process-produce-a-heap-dump-on-an-outofmemorye">Is有没有办法有一个Android程序产生堆转储上一个OutOfMemoryError?

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?

推荐答案

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

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... :)

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

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

(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.

这篇关于Android的StrictMode和堆转储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆