有没有办法有一个Android的过程中产生的堆转储对一个OutOfMemoryError?没有办法、过程中、有一个、Android

2023-09-12 11:07:59 作者:哽咽一句 我想你了

Sun JVM的支持 -XX:+ HeapDumpOnOutOfMemoryError 选项转储堆每当一个java进程耗尽堆

The sun JVM supports a -XX:+HeapDumpOnOutOfMemoryError option to dump heap whenever a java process runs out of heap.

有没有在Android上的类似选项,这将使Android应用程序转储堆在一个OutOfMemoryException?它可以是很难尝试手动使用DDMS的时候适当地计时。

Is there a similar option on Android that will make an android app dump heap on an OutOfMemoryException? It can be difficult to try to time it properly when using DDMS manually.

推荐答案

要扩大在CommonsWare的回答是:

To expand upon CommonsWare's answer:

我不知道这是否正常工作,但你可以尝试adding顶层异常处理程序和在那里asking对于堆转储如果它是一个的OutOfMemoryError

I have no idea if this works, but you might try adding a top-level exception handler, and in there asking for a heap dump if it is an OutOfMemoryError.

我跟着他的建议成功地在自己与下面的code Android应用:

I followed his suggestion successfully in my own Android app with the following code:

public class MyActivity extends Activity {
    public static class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
        @Override
        public void uncaughtException(Thread thread, Throwable ex) {
            Log.e("UncaughtException", "Got an uncaught exception: "+ex.toString());
            if(ex.getClass().equals(OutOfMemoryError.class))
            {
                try {
                    android.os.Debug.dumpHprofData("/sdcard/dump.hprof");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            ex.printStackTrace();
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Thread.currentThread().setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
    }
}

创建转储

后,您需要将其从手机复制到PC:点击打开USB存储设备的电话,找到该文件,并将其复制到硬盘上

After the dump is created, you need to copy it from your phone to your PC: Click "Turn on USB storage" on the phone, find the file and copy it to your hard drive.

然后,如果你想使用Eclipse的内存分析器(MAT)分析文件,你需要隐蔽的文件: HPROF-conv.exe dump.hprof自卸conv.hprof (HPROF-CONV位于 Android的SDK /工具

Then, if you want to use the Eclipse Memory Analyzer (MAT) to analyze the file, you will need to covert the file: hprof-conv.exe dump.hprof dump-conv.hprof (hprof-conv is located under android-sdk/tools)

最后,打开自卸conv.hprof 与MAT文件

Finally, open the dump-conv.hprof file with MAT