• 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

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

  • 相关阅读:
    FlexGrid布局
    Grid 布局管理器
    StaticBox布局管理器
    鼠标事件
    screen 常用命令
    wxPython 安装 及参考文档
    wxPython 界面编程的有关事件
    关于用python作为第三方程序,来调用shell命令的问题,以及返回值格式解析
    Mysql的增删改查
    linux ubuntu 系统修改源
  • 原文地址:https://www.cnblogs.com/blfshiye/p/5154933.html
Copyright © 2020-2023  润新知