• 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

    代码是自己的。尽管简单,算我是原创吧。不然。真的非常难装逼。哭

  • 相关阅读:
    python3.6 range() 函数
    常见文件头,文件尾总结。
    pycharm多行代码注释,或取消。
    php设计模式之命令模式
    php设计模式之工厂模式
    php设计模式之观察者模式
    SQLServer导出sql文件,导出表架构和数据
    vs2012建设网站,IIS8发布
    Subsonic 配置文件
    去掉txt中的重复标题
  • 原文地址:https://www.cnblogs.com/blfshiye/p/5154933.html
Copyright © 2020-2023  润新知