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

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

实现步骤:

  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**

你可能感兴趣的:(自定义全局未处理异常捕捉器)