自定义全局未处理异常捕捉器

作者: 大话程序 | 来源:发表于2016-12-07 16:24 被阅读116次

在开发过程中或者在程序正式上线以后,总是或多或少的出现程序崩溃的情况,大多是程序在测试的时候,没有完整测试。此时,自定义全局未处理异常捕捉器就显得非常有用了

实现步骤:

  1. 自定义全局未处理异常捕捉器,需要实现UncaughtExceptionHandler接口,并重写uncaughtException(Thread thread, Throwable ex)方法
  2. Application或者主页面Activity或者某个Activity中,调用方法Thread.setDefaultUncaughtExceptionHandler,设置自定义的异常捕捉器为默认的全局异常捕捉器

实现栗子

在主页面中设置异常捕捉器,在第二个界面中发生异常,提示用户程序崩溃,将异常原因以文本形式保存到本地,重新启动程序进入主页面

自定义异常捕捉器:

public class MyExceptionHanlder implements UncaughtExceptionHandler {

    private Context mContext = null;
    private String className = "";

    public MyExceptionHanlder(Context context) {
        this.mContext = context;
    }

    public MyExceptionHanlder(Context context, String className) {
        this.mContext = context;
        this.className = className;
    }

    /**
     * 当自定义的异常捕获异常处理器被设置为此APP默认的异常处理器,
     * 发生未处理异常时,此方法会被自动调用
     * @param thread 所发生异常所在的线程
     * @param ex 抛出的未处理异常Throwable对象
     */
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if (ex != null) {
            Log.i("UncaughtException", ex.getMessage());
            StringBuilder sb = new StringBuilder();
            String temp = ex.getMessage();
            if (temp != null) {
                sb.append("ex.getMessage():");
                sb.append(System.getProperty("line.separator"));
                sb.append(temp);
            }
            sb.append(System.getProperty("line.separator"));
            sb.append("thread.getName():" + thread.getName());
            sb.append(System.getProperty("line.separator"));
            sb.append(" Trace: " + System.getProperty("line.separator"));
            StackTraceElement[] elements = ex.getStackTrace();
            if (elements != null) {
                for (StackTraceElement element : elements) {
                    temp = element.toString();
                    if (temp != null) {
                        sb.append(temp);
                    }
                    sb.append(System.getProperty("line.separator"));
                }
            }

            sb.append("Cause: ");
            sb.append(System.getProperty("line.separator"));
            Throwable theCause = ex.getCause();
            if (theCause != null) {
                temp = theCause.toString();
                if (temp != null) {
                    sb.append(temp);
                }
            }
            sb.append(System.getProperty("line.separator") + " Cause Stack: " +
                    System.getProperty("line.separator"));
            theCause = ex.getCause();
            if (theCause != null) {
                elements = theCause.getStackTrace();
                if (elements != null) {
                    for (StackTraceElement element : elements) {
                        temp = element.toString();
                        if (temp != null) {
                            sb.append(temp);
                        }
                        sb.append(System.getProperty("line.separator"));
                    }
                }
            }

            try {
                //将异常信息存入本地文件
                this.writeCrashLog(sb);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //弹出自定义处理异常界面
            Intent intent = new Intent(mContext, ExceptionDialog.class);
            intent.putExtra("className", className);
            mContext.startActivity(intent);
            //销毁页面,杀死APP进程
            crash(mContext);

        }
    }

    /**
     * 将异常信息存入本地信息
     * @param sb StringBuilder对象
     * @throws Exception 抛出异常对象
     */
    private void writeCrashLog(StringBuilder sb) throws Exception {
        //存储路径
        String path = Environment.getExternalStorageDirectory() + "/crashLog.txt";
        Log.d("Main", path);
        File logFile = new File(path);
        if (!logFile.exists()){
            logFile.createNewFile();
        }else{
            logFile.delete();
            logFile.createNewFile();
        }
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(logFile));
        bufferedWriter.write(sb.toString());
        bufferedWriter.close();
        Toast.makeText(mContext, "写入成功", Toast.LENGTH_LONG).show();
    }

    /**
     * 销毁页面以及关闭APP进程
     * @param context 上下文对象
     * @return 是否销毁页面以及当前进程
     */
    public static boolean crash(Context context) {
        if (context == null) {
            return false;
        }
        //销毁页面
        if (context instanceof Activity) {
            ((Activity) context).finish();
        }
        //杀死APP进程
        Process.killProcess(Process.myPid());
        return true;
    }

**源文件下载地址:http://download.csdn.net/detail/xiaoshengfdyh/9704576**

相关文章

  • 自定义全局未处理异常捕捉器

    在开发过程中或者在程序正式上线以后,总是或多或少的出现程序崩溃的情况,大多是程序在测试的时候,没有完整测试。此时,...

  • 捕捉未处理异常

    According to the Java API documentation, when a thread is...

  • SpringBoot异常处理

    1. 配置全局异常和自定义异常 异常处理类(包括全局和自定义) 自定义异常类 2.返回自定义页面 创建自定义页面位...

  • Spring中通过@ControllerAdvice统一异常处理

    通过继承异常类自定义异常: 编写全局异常处理器并使用@ControllerAdvice修饰:(从名字可以看出该注解...

  • WPF捕获全局未处理异常

    WPF中捕获全局异常并记录 应用有时候会异常崩溃,这时候如果有错误的堆栈信息,就很方便我们查找问题。捕获未处理异常...

  • SpringBoot全局异常捕捉

    一、引言 web开发的时候,请求500,404等错误,为了界面友好化,整个站点抛任何异常的,全部拦截,统一返回 二...

  • 捕捉RxJava全局异常

    参考资料:https://github.com/ReactiveX/RxJava/wiki/Error-Handling

  • 捕捉RxJava全局异常

    参考资料:https://github.com/ReactiveX/RxJava/wiki/Error-Handling

  • 全局 Promise 异常捕捉

    《深入理解ES6》阅读随笔 在 ES6 的 Promise 中,对于直接 reject 的异常未处理任务,不会进行...

  • CrashHandler全局捕捉异常

    前言 在Android开发中,捕获异常是件十分重要的事。修复bug都是从捕捉bug信息开始。在上一节中,我们已经讲...

网友评论

    本文标题:自定义全局未处理异常捕捉器

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