美文网首页
(转)Android生成heap dump文件(.hprof)

(转)Android生成heap dump文件(.hprof)

作者: 匡风含情 | 来源:发表于2016-11-14 20:27 被阅读462次

转自:http://blog.csdn.net/sodino/article/details/38512473

一个heap dump就是一个程序heap的快照,可以获知程序的哪些部分正在使用大部分的内存。
它保存为一种叫做HPROF的二进制格式。对于Android执行android.os.Debug.dumpHprofData(hprofPath)方法后所生成的文件,需要把.hprof文件从Dalvik格式转换成J2SE HPROF格式。使用AndroidSDK提供的hprof-conv工具可执行该转换操作。

hprof-conv dump.hprof converted-dump.hprof  

Android代码生成dump文件如下:

    public static boolean createDumpFile(Context context) {
        String LOG_PATH = "/dump.gc/";
        boolean bool = false;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH.mm.ssss", Locale.getDefault());
        String createTime = sdf.format(new Date(System.currentTimeMillis()));
        String state = android.os.Environment.getExternalStorageState();
        
        // 判断SdCard是否存在并且是可用的
        if (android.os.Environment.MEDIA_MOUNTED.equals(state)) {
            File file = new File(Environment.getExternalStorageDirectory().getPath() + LOG_PATH);
            if (!file.exists()) {
                file.mkdirs();
            }
            
            String hprofPath = file.getAbsolutePath();
            if (!hprofPath.endsWith("/")) {
                hprofPath += "/";
            }

            hprofPath += createTime + ".hprof";
            try {
                android.os.Debug.dumpHprofData(hprofPath);
                bool = true;
                Log.d("nsz", "create dumpfile done!");
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            bool = false;
            Log.d("nsz", "no sdcard!");
        }

        return bool;
    }

不要忘记了在AndroidManifest.xml中声明SDCard写权限:

<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE" />  

相关文章

网友评论

      本文标题:(转)Android生成heap dump文件(.hprof)

      本文链接:https://www.haomeiwen.com/subject/zrqkpttx.html