19

Sun JVMは-XX:+HeapDumpOnOutOfMemoryError、Javaプロセスがヒープを使い果たしたときにヒープをダンプするオプションをサポートしています。

OutOfMemoryExceptionでAndroidアプリのダンプヒープを作成するAndroidの同様のオプションはありますか?DDMSを手動で使用する場合、適切なタイミングをとることが難しい場合があります。

4

3 に答える 3

28

CommonsWareの答えを拡張するには:

これが機能するかどうかはわかりませんが、トップレベルの例外ハンドラーを追加して、ヒープダンプがであるかどうかを確認してみてOutOfMemoryErrorください。

私は次のコードを使用して、自分のAndroidアプリで彼の提案にうまく従いました。

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ストレージをオンにする]をクリックし、ファイルを見つけてハードドライブにコピーします。

次に、Eclipse Memory Analyzer(MAT)を使用してファイルを分析する場合は、ファイルを秘密にする必要があります:hprof-conv.exe dump.hprof dump-conv.hprof(hprof-convはの下にありますandroid-sdk/tools

最後に、dump-conv.hprofMATでファイルを開きます

于 2011-08-03T20:22:11.620 に答える
11

これが機能するかどうかはわかりませんが、トップレベルの例外ハンドラーを追加して、ヒープダンプがであるかどうかを確認してみてOutOfMemoryErrorください。

于 2011-05-25T23:43:40.283 に答える
11

これが改良版です。元の実装に加えて、この実装は以下もサポートします。

  • すべてのスレッド(メインスレッドだけでなく)でのメモリ不足エラーのキャッチ
  • 別のエラーの中に隠されている場合でも、メモリ不足エラーを識別します。場合によっては、メモリ不足エラーがランタイムエラー内にカプセル化されます。
  • 元のデフォルトのキャッチされていない例外ハンドラーも呼び出します。
  • DEBUGビルドでのみ機能します。

使用法: onCreateinitializeメソッドのApplicationクラスの静的メソッドを呼び出します。

package test;
import java.io.File;
import java.io.IOException;
import java.lang.Thread.UncaughtExceptionHandler;

import android.os.Environment;
import android.util.Log;

import com.example.test1.BuildConfig;

public class OutOfMemoryDumper implements Thread.UncaughtExceptionHandler {

    private static final String TAG = "OutOfMemoryDumper";
    private static final String FILE_PREFIX = "OOM-";
    private static final OutOfMemoryDumper instance = new OutOfMemoryDumper();

    private UncaughtExceptionHandler oldHandler;

    /**
     * Call this method to initialize the OutOfMemoryDumper when your
     * application is first launched.
     */
    public static void initialize() {

        // Only works in DEBUG builds
        if (BuildConfig.DEBUG) {
            instance.setup();
        }
    }

    /**
     * Keep the constructor private to ensure we only have one instance
     */
    private OutOfMemoryDumper() {
    }

    private void setup() {

        // Checking if the dumper isn't already the default handler
        if (!(Thread.getDefaultUncaughtExceptionHandler() instanceof OutOfMemoryDumper)) {

            // Keep the old default handler as we are going to use it later
            oldHandler = Thread.getDefaultUncaughtExceptionHandler();

            // Redirect uncaught exceptions to this class
            Thread.setDefaultUncaughtExceptionHandler(this);
        }
        Log.v(TAG, "OutOfMemoryDumper is ready");
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {

        Log.e(TAG, "Uncaught exception: " + ex);
        Log.e(TAG, "Caused by: " + ex.getCause());

        // Checking if the exception or the original cause for the exception is
        // an out of memory error
        if (ex.getClass().equals(OutOfMemoryError.class)
                || (ex.getCause() != null && ex.getCause().getClass()
                        .equals(OutOfMemoryError.class))) {

            // Checking if the external storage is mounted and available
            if (isExternalStorageWritable()) {
                try {

                    // Building the path to the new file
                    File f = Environment
                            .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

                    long time = System.currentTimeMillis();

                    String dumpPath = f.getAbsolutePath() + "/" + FILE_PREFIX
                            + time + ".hprof";

                    Log.i(TAG, "Dumping hprof data to: " + dumpPath);

                    android.os.Debug.dumpHprofData(dumpPath);

                } catch (IOException ioException) {
                    Log.e(TAG,"Failed to dump hprof data. " + ioException.toString());
                    ioException.printStackTrace();
                }
            }
        }

        // Invoking the original default exception handler (if exists)
        if (oldHandler != null) {
            Log.v(TAG, "Invoking the original uncaught exception handler");
            oldHandler.uncaughtException(thread, ex);
        }
    }

    /**
     * Checks if external storage is available for read and write
     * 
     * @return true if the external storage is available
     */
    private boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        Log.w(TAG,"The external storage isn't available. hprof data won't be dumped! (state=" + state + ")");
        return false;
    }
}
于 2014-09-29T21:47:17.027 に答える