Android崩溃后重启
16lz
2021-01-23
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中主动抛出下面异常,就会发现应用遇到异常后重启了,如果不处理的话,应用在遇到异常后就关闭了。
更多相关文章
- android将线程绑定在指定CPU
- Android AM命令行启动程序的方法
- android studio中运行main方法报错问题解决方法
- Android Studio 解决方法No JVM installation found. Please ins
- Ubuntu环境下Android源码下载及编译方法
- android的多线程操作(一)
- android之发送短信的方法研究
- 小心XmlPullParser.netText()方法
- [Android] Android获取当前顶部Activity名方法历史版本汇总