Thread.UncaughtExceptionHandler 接口并复写uncaughtException(Thread thread, Throwable ex)方法来实现对运行时线程进行异常处理。在Android中我们可以实现自己的Application类,然后实现 UncaughtExceptionHandler接口,并在uncaughtException方法中处理异常,这里我们关闭App并启动我们需要的Activity,下面看代码:
ps:MainActivity为应用的启动Activity
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
public
class
MyApplication
extends
Application
implements
Thread.UncaughtExceptionHandler {
@Override
public
void
onCreate() {
super
.onCreate();
//设置Thread Exception Handler
Thread.setDefaultUncaughtExceptionHandler(
this
);
}
@Override
public
void
uncaughtException(Thread thread, Throwable ex) {
//设置此处的MainActivity为启动Activity
Intent intent =
new
Intent(
this
, MainActivity.
class
);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
|
我们在任意一个Activity中主动抛出下面异常,就会发现应用遇到异常后重启了,如果不处理的话,应用在遇到异常后就关闭了。
本文介绍如何通过实现Thread.UncaughtExceptionHandler接口并在uncaughtException方法中处理异常,使Android应用在遇到未捕获异常时能够自动重启,从而提高用户体验。

被折叠的 条评论
为什么被折叠?



