在Android应用开发中,偶尔会因为某些异常导致正在使用的应用出现异常并强制关闭,这样导致不友好的用户体验。为了解决这个问题,我们需要捕获出现的异常并做处理。在Java中有两类异常,分别是Error和RuntimeException,前者是不需要我们去处理的,我们处理的往往是后者。那么如何捕获线程在运行时的异常呢,我们可以使用自定义类实现
最后需要在Manifest中配置Application的标签android:name=".MyApplication",让整个应用程序使用我们自定义的Application类,这样就实现了当应用遇到崩溃异常时重启应用的效果。
Thread.UncaughtExceptionHandler 接口并复写uncaughtException(Thread thread, Throwable ex)方法来实现对运行时线程进行异常处理。在Android中我们可以实现自己的Application类,然后实现 UncaughtExceptionHandler接口,并在uncaughtException方法中处理异常,这里我们关闭App并启动我们需要的Activity,下面看代码:
|
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) { |
|
System.out.println( "uncaughtException" ); |
|
System.exit( 0 ); |
|
Intent
intent = new Intent( this ,
MainActivity. class ); |
|
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| |
|
Intent.FLAG_ACTIVITY_NEW_TASK); |
|
startActivity(intent); |
|
} |
|
|
|
} |
我们在任意一个Activity中主动抛出下面异常,就会发现应用遇到异常后重启了,如果不处理的话,应用在遇到异常后就关闭了。