内存泄漏Exception类-OomExceptionHandler

package com.jaeger.ninegridimgdemo.entity;

import android.content.Context;
import android.os.Debug;

import java.io.File;
import java.io.IOException;

/**
 * Created by 杨阳洋 on 2017/11/23.
 * usg:OOM异常
 */

public class OomExceptionHandler implements Thread.UncaughtExceptionHandler {

    private static final String FILENAME = "out-of-memory.hprof";
    private final Thread.UncaughtExceptionHandler defaultHandler;
    private final Context context;

    public static void install(Context context){
        Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
        if(defaultUncaughtExceptionHandler instanceof OutOfMemoryError) {
            return;
        }
        OomExceptionHandler oomHandler = new OomExceptionHandler(defaultUncaughtExceptionHandler, context);
        Thread.setDefaultUncaughtExceptionHandler(oomHandler);
    }

    public OomExceptionHandler(Thread.UncaughtExceptionHandler defaultHandler, Context context) {
        this.defaultHandler = defaultHandler;
        this.context = context.getApplicationContext();
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if(containsOom(ex)) {
            File heapDumpFile = new File(context.getFilesDir(), FILENAME);
            try {
                Debug.dumpHprofData(heapDumpFile.getAbsolutePath());
            } catch (IOException e) {

            }
        }
        defaultHandler.uncaughtException(thread, ex);
    }

    private boolean containsOom(Throwable ex){
        if(ex instanceof OutOfMemoryError) {
            return true;
        }
        while ((ex = ex.getCause()) != null){
            if(ex instanceof OutOfMemoryError) {
                return true;
            }
        }
        return false;
    }

}

你可能感兴趣的:(内存泄漏Exception类-OomExceptionHandler)