博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
android捕获程序异常退出
阅读量:7034 次
发布时间:2019-06-28

本文共 2098 字,大约阅读时间需要 6 分钟。

今天看到迅雷动漫里面一个CrashHandler 的类,我猜是崩溃处理类。进去一看。果然。顺便学习一下。

Android系统的“程序异常退出”,给应用的用户体验造成不良影响。为了捕获应用执行时异常并给出友好提示,便可继承类来处理。

通过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);        }    }}
两个能够看的參考:

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

你可能感兴趣的文章
一个完整的搜索系统 - God bless you - 博客园
查看>>
Java中List转换为Array
查看>>
跨浏览器开发:CSS代码的金科玉律
查看>>
钱币换算
查看>>
mysql 服务无法启动
查看>>
修改和添加Apache的默认站点目录
查看>>
UserAgent
查看>>
Tomcat 7绑定域名
查看>>
[PAL编程规范]SAP HANA PAL逻辑回归预测分析Logistic Regression编程规范FORECASTWITHLOGISTICR(预测)...
查看>>
oracle 当前用户进程个数
查看>>
php empty,isset,is_null比较(差异与异同)
查看>>
SQL存储过程动态查询数据区间
查看>>
【送给新手】重复代码解决示例二
查看>>
c++ static
查看>>
C++中extern “C”含义深层探索
查看>>
磁盘分区对齐的重要性
查看>>
MVC3和MVC4相关问题
查看>>
Django文档——Model字段选项(Field Options)
查看>>
关于ARM NEON学习的一些资料
查看>>
火车运煤问题
查看>>