android捕获程序异常退出
今天看到迅雷动漫里面一个CrashHandler 的类,我猜是崩溃处理类。进去一看,果然。顺便学习一下。
Android系统的“程序异常退出”,给应用的用户体验造成不良影响。为了捕获应用运行时异常并给出友好提示,便可继承UncaughtExceptionHandler类来处理。通过Thread.setDefaultUncaughtExceptionHandler()方法将异常处理类设置到线程上即可。
代码:
public class CrashHandler implements UncaughtExceptionHandler { private static final Logger LOG = Logger.getLogger(CrashHandler.class); private final Application mApplication; private Handler mUIHandler; private Thread mUiThread; public CrashHandler(Application app) { mApplication = app; mUIHandler = new Handler(); mUiThread = Thread.currentThread(); } @Override public void uncaughtException(Thread thread, Throwable e) { LOG.error(e); Throwable cause = e.getCause(); while (cause != null) { LOG.error(cause); cause = cause.getCause(); } writeCrashInfoToFile(e); if (Thread.currentThread() != mUiThread) { mUIHandler.post(new Runnable() { @Override public void run() { mApplication.onTerminate(); } }); } else { mApplication.onTerminate(); } } private void writeCrashInfoToFile(Throwable t) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); Throwable cause = t.getCause(); while (cause != null) { cause.printStackTrace(pw); cause = cause.getCause(); } String crashInfo = sw.toString(); pw.close(); try { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { File file = mApplication.getApplicationContext().getExternalCacheDir(); if (file != null) { file = FileUtils.getFile(file, "crash"); file.mkdirs(); FileUtils.writeStringToFile(FileUtils.getFile(file, "crash.log"), crashInfo); } } } catch (IOException e) { LOG.warn(e); } } }两个可以看的参考:
http://blog.csdn.net/hehe9737/article/details/7662123
http://blog.csdn.net/wangbole/article/details/8161524
代码是自己的,虽然简单,算我是原创吧。不然,真的很难装逼。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。