閱讀204 返回首頁    go 阿裏雲 go 技術社區[雲棲]


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);
        }
    }
}
兩個可以看的參考:

https://blog.csdn.net/hehe9737/article/details/7662123

https://blog.csdn.net/wangbole/article/details/8161524

代碼是自己的,雖然簡單,算我是原創吧。不然,真的很難裝逼。哭

最後更新:2017-04-03 05:40:10

  上一篇:go android 滾輪刻度尺的實現
  下一篇:go 【OpenCV】訪問Mat圖像中每個像素的值 (II)