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);          System.exit(0); 
             }
最后需要在Manifest中配置Application的标签android:name=".MyApplication",让整个应用程序使用我们自定义的Application类,这样就实现了当应用遇到崩溃异常时重启应用的效果。

我们在任意一个Activity中主动抛出下面异常,就会发现应用遇到异常后重启了,如果不处理的话,应用在遇到异常后就关闭了。


更多相关文章

  1. android将线程绑定在指定CPU
  2. Android AM命令行启动程序的方法
  3. android studio中运行main方法报错问题解决方法
  4. Android Studio 解决方法No JVM installation found. Please ins
  5. Ubuntu环境下Android源码下载及编译方法
  6. android的多线程操作(一)
  7. android之发送短信的方法研究
  8. 小心XmlPullParser.netText()方法
  9. [Android] Android获取当前顶部Activity名方法历史版本汇总

随机推荐

  1. Android(安卓)studio device error
  2. no
  3. IP地址获取
  4. 编写Wifi程序需要在AndroidMinifest中添
  5. ExpandableButtonMenu |底部弹出菜单
  6. Android(安卓)编译的几个命令
  7. Android开发之OpenGL+ES教程
  8. Android(安卓)Sqlite Locking
  9. android XML 画图
  10. 回弹ScrollView