Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android捕獲程序異常退出

android捕獲程序異常退出

編輯:關於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);
        }
    }
}
 
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved