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
public
class
CrashHandler
implements
UncaughtExceptionHandler {
public
static
final
String TAG = CopyOfCrashHandler.
class
.getSimpleName();
// 系统默认的UncaughtException处理类
private
Thread.UncaughtExceptionHandler mDefaultHandler;
private
static
CopyOfCrashHandler instance;
private
Context mContext;
private
CopyOfCrashHandler() {
}
/** 获取CrashHandler实例 ,单例模式 */
public
static
CopyOfCrashHandler getInstance() {
if
(instance ==
null
)
instance =
new
CopyOfCrashHandler();
return
instance;
}
/**
* 初始化
*/
public
void
init(Context context) {
mContext = context;
//记录下默认的UncaughtExceptionHandler
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
//
Thread.setDefaultUncaughtExceptionHandler(
this
);
}
/**
* 当UncaughtException发生时会转入该函数来处理
*/
@Override
public
void
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.
*/
private
boolean
handleException(Thread thread, Throwable ex) {
if
(ex ==
null
) {
return
false
;
}
StringBuffer sb =
new
StringBuffer();
sb.append(thread +
", Cause By:"
+ ex).append(
"\r\n\r\n"
);
StackTraceElement[] elements = ex.getStackTrace();
for
(
int
i =
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()), "程序出现异常,请记录时间并提示开发人员!");
return
true
;
}
}
0 0
- Android_程序未处理异常的捕获与处理
- Android_程序未处理异常的捕获与处理
- AppDomain的两个小技巧(程序运行完毕和未处理异常的处理) 捕获未处理异常
- C# 捕获未处理的异常
- WPF捕获未处理的异常
- 未处理异常的处理
- 捕获asp.net下的未处理异常
- C# WinForm捕获未处理的异常
- C# WinForm捕获未处理的异常
- C# WinForm捕获未处理的异常
- C#_WinForm 统一捕获未处理的异常
- 捕获asp.net下的未处理异常
- C# WinForm捕获全局异常(捕获未处理的异常)
- 异常的捕获与处理
- 异常的捕获与处理
- C#捕获未处理异常
- nodejs 捕获未处理异常
- 如何处理Windows Forms程序中未处理的异常
- WebView的基本使用
- 简单申请列表状态数据处理 yii2
- 【进程通信】无名管道 and 有名管道
- Pick Several Elements From a Vector Randomly
- struts2 学习笔记
- Android_程序未处理异常的捕获与处理
- POJ 3087 模拟+hash
- 阿里面试回来,想和Java程序员谈一谈
- 【noip2015】【DP】子串
- Yii2 - 03视图(View)操作,以及Layout的使用
- 静态链表的实现
- item点击回调封装(改变带来Position的参数)
- lintcode Max Points on a Line
- 使用Loader加载本地图片