码迷,mamicode.com
首页 > 移动开发 > 详细

android捕获程序异常退出

时间:2014-09-01 19:38:43      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:android异常   uncaughtexceptionhan   

今天看到迅雷动漫里面一个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

代码是自己的,虽然简单,算我是原创吧。不然,真的很难装逼。bubuko.com,布布扣

android捕获程序异常退出

标签:android异常   uncaughtexceptionhan   

原文地址:http://blog.csdn.net/minimicall/article/details/38983419

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!