UncaughtExceptionHandler异常捕获,并存储到本地目录

项目反馈使用过程中奔溃退出了,但是却没有在第三方SDK收集到。所以考虑使用本地收集异常的方式,当产生异常时,可以把  
记录保存到磁盘中的位置,方便开发取出日志直接定位问题。  
android 使用Thread.UncaughtExceptionHandler进行全局异常捕获,该接口只有一个方法需要实现:
void uncaughtException(Thread t, Throwable e); 
文档连接:
https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.UncaughtExceptionHandler.html
以下是官网文档对于该接口的描述  
当一个线程即将因未捕获的异常而终止时,Java虚拟机将使用thread.getUncaughtExceptionHandler()查询该线程的  
uncaughtException处理程序,并调用该处理程序的uncaughtException方法,将线程和异常作为参数传递。如果一个  
线程没有显式设置其UncaughtExceptionHandler,则其ThreadGroup对象充当其Uncaught ExceptionHandler。如果  
ThreadGroup对象对处理异常没有特殊要求,它可以将调用转发给默认的未捕获异常处理程序。  

使用UncaughtExceptionHandler捕获异常  
1.自定义UncaughtExceptionHandler,实现UncaughtExceptionHandler接口  
2.记录系统默认的UncaughtExceptionHandler,通过Thread.getDefaultUncaughtExceptionHandler()获取默认的异常处理器  
3.在uncaughtException()方法中处理异常,这里只需要保存到磁盘中的文件  
4.如果自定义处理器没有处理的情况才继续使用默认的处理  
5.产生异常保存文件路劲在外部存储目录\Android\data\包名\\files\exception目录下

完整代码如下:
MyApplication.java:
public class MyApplication extends Application {
    MyExceptionHandler handler = null;

    @Override
    public void onCreate() {
        super.onCreate();
        handler = MyExceptionHandler.getInstance();
        handler.init(getApplicationContext());
    }
}
MyExceptionHandler.java:
public class MyExceptionHandler implements Thread.UncaughtExceptionHandler {

    public static final String TAG = MyExceptionHandler.class.getSimpleName();

    private Thread.UncaughtExceptionHandler mDefaultUncaughtExceptionHandler;

    private static MyExceptionHandler INSTANCE;

    private Context mContext;

    private Map<String, String> deviceInfoMap = new HashMap<>();

    private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss  ");

    private MyExceptionHandler() {
    }

    public static MyExceptionHandler getInstance() {
        if (INSTANCE == null) {
            synchronized(MyExceptionHandler.class) {
                if (INSTANCE == null) {
                    INSTANCE = new MyExceptionHandler();
                }
            }
        }
        return INSTANCE;
    }

    /**
     * 初始化
     *
     * @param context
     */
    public void init(Context context) {
        mContext = context;
        mDefaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    /**
     * 当UncaughtException发生时会转入该函数来处理
     */
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if (!handleException(ex) && mDefaultUncaughtExceptionHandler != null) {
            mDefaultUncaughtExceptionHandler.uncaughtException(thread, ex);
        } else {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                Log.e(TAG, "error : ", e);
            }
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(1);
        }
    }

    /**
     * 自己定义错误处理,收集错误信息 发送错误报告等操作均在此完毕.
     *
     * @param ex
     * @return true:假设处理了该异常信息;否则返回false.
     */
    private boolean handleException(final Throwable ex) {
        if (ex == null) {
            return false;
        }
        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                ex.printStackTrace();
                Toast.makeText(mContext, "非常抱歉,程序出现异常,即将退出.", Toast.LENGTH_LONG).show();
                Looper.loop();
            }
        }.start();
        collectDeviceInfo(mContext);
        saveCrashInfo2File(ex);
        return true;
    }

    /**
     * 收集设备參数信息
     *
     * @param ctx
     */
    public void collectDeviceInfo(Context ctx) {
        try {
            PackageManager pm = ctx.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);
            if (pi != null) {
                String versionName = pi.versionName == null ? "null" : pi.versionName;
                String versionCode = pi.versionCode + "";
                deviceInfoMap.put("versionName", versionName);
                deviceInfoMap.put("versionCode", versionCode);
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, "an error occured when collect package info", e);
        }
        Field[] fields = Build.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                deviceInfoMap.put(field.getName(), field.get(null).toString());
                Log.d(TAG, field.getName() + " : " + field.get(null));
            } catch (Exception e) {
                Log.e(TAG, "an error occured when collect crash info", e);
            }
        }
    }

    /**
     * 保存错误信息到文件里
     *
     * @param ex
     * @return 返回文件名称称,便于将文件传送到server
     */
    private String saveCrashInfo2File(Throwable ex) {
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> entry : deviceInfoMap.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            sb.append(key + "=" + value + "\n");
        }

        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        String result = writer.toString();
        String time = formatter.format(new Date());
        sb.append(time + result);
        try {
            String fileName = formatter.format(new Date()) + "exception.log";
            File externalFile = mContext.getExternalFilesDir(null);
            if (externalFile != null && !TextUtils.isEmpty(externalFile.getAbsolutePath())) {
                String path = externalFile.getAbsolutePath() + "/exception/";
                File dir = new File(path);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                FileOutputStream fos = new FileOutputStream(path + fileName, true);
                fos.write((sb.toString()).getBytes());
                fos.close();
            } else {
                Log.e(TAG, "file path is null");
            }
            return fileName;
        } catch (Exception e) {
            Log.e(TAG, "an error occured while writing file...", e);
        }
        return null;
    }
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值