Android_程序未处理异常的捕获与处理

来源:互联网 发布:网络调试助手使用说明 编辑:程序博客网 时间:2024/05/19 12:13

1.简介

对于程序抛出的未被捕获的异常,可能会导致程序异常退出,界面不友好且应记录关键错误信息上传至服务器。这里主要使用UncaughtExceptionHandler

2.代码实现

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
publicclass CrashHandler implementsUncaughtExceptionHandler {
    publicstatic final String TAG = CopyOfCrashHandler.class.getSimpleName();
 
    // 系统默认的UncaughtException处理类
    privateThread.UncaughtExceptionHandler mDefaultHandler;
    privatestatic CopyOfCrashHandler instance;
    privateContext mContext;
 
    privateCopyOfCrashHandler() {
    }
 
    /** 获取CrashHandler实例 ,单例模式 */
    publicstatic CopyOfCrashHandler getInstance() {
        if(instance == null)
            instance = newCopyOfCrashHandler();
        returninstance;
    }
 
    /**
     * 初始化
     */
    publicvoid init(Context context) {
        mContext = context;
        //记录下默认的UncaughtExceptionHandler
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        //
        Thread.setDefaultUncaughtExceptionHandler(this);
    }
 
    /**
     * 当UncaughtException发生时会转入该函数来处理
     */
    @Override
    publicvoid uncaughtException(Thread thread, Throwable ex) {
        if(!handleException(thread, ex) && mDefaultHandler != null) {
            // 如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, ex);
        }else{
            try{
                Thread.sleep(1000);
            }catch(InterruptedException e) {
                e.printStackTrace();
            }
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(1);
        }
    }
 
    /**
     * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
     *
     * @param ex
     * @return true:如果处理了该异常信息;否则返回false.
     */
    privateboolean handleException(Thread thread, Throwable ex) {
        if(ex == null) {
            returnfalse;
        }
 
        StringBuffer sb = newStringBuffer();
        sb.append(thread + ", Cause By:" + ex).append("\r\n\r\n");
 
        StackTraceElement[] elements = ex.getStackTrace();
        for(inti = 0; i < elements.length; i++) {
            sb.append(elements[i].toString() + "\r\n");
        }
        //记录下关键错误信息,可以存至本地并上传至服务器
        //LogUtil.bug(TAG, sb.toString());
         
        //打开新Activity友好界面提示
        //Util.showDialog(mContext, "时间:"+Util.formatSimpleDateAndTime(new Date()), "程序出现异常,请记录时间并提示开发人员!");
        returntrue;
    }
}
0 0