Android使用UncaughtExceptionHandler捕獲全局異常

   UncaughtExceptionHandler可以用來捕獲程序異常,比如NullPointerException空指針異常拋出時,用戶沒有try catch捕獲,那麼,Android系統會彈出對話框的“XXX程序異常退出”,給應用的用戶體驗造成不良影響。爲了捕獲應用運行時異常並給出友好提示,便可繼承UncaughtExceptionHandler類來處理。

1、異常處理類,代碼如下:

public class CrashHandler implements UncaughtExceptionHandler {
	private static final String TAG = CrashHandler.class.getSimpleName();

	private static CrashHandler instance; // 單例模式

    private OnBeforeHandleExceptionListener mListener;

	private Context context; // 程序Context對象
	private Thread.UncaughtExceptionHandler defalutHandler; // 系統默認的UncaughtException處理類
	private DateFormat formatter = new SimpleDateFormat(
			"yyyy-MM-dd_HH-mm-ss.SSS", Locale.CHINA);

	private CrashHandler() {

	}

	/**
	 * 獲取CrashHandler實例
	 * 
	 * @return CrashHandler
	 */
	public static CrashHandler getInstance() {
		if (instance == null) {
			synchronized (CrashHandler.class) {
				if (instance == null) {
					instance = new CrashHandler();
				}
			}
		}

		return instance;
	}

	/**
	 * 異常處理初始化
	 * 
	 * @param context
	 */
	public void init(Context context) {
		this.context = context;
		// 獲取系統默認的UncaughtException處理器
		defalutHandler = Thread.getDefaultUncaughtExceptionHandler();
		// 設置該CrashHandler爲程序的默認處理器
		Thread.setDefaultUncaughtExceptionHandler(this);
	}

	/**
	 * 當UncaughtException發生時會轉入該函數來處理
	 */
	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
        //異常發生時,先給藍牙服務端發送OK命令
        if (mListener != null) {
            mListener.onBeforeHandleException();
        }

		// 自定義錯誤處理
		boolean res = handleException(ex);
		if (!res && defalutHandler != null) {
			// 如果用戶沒有處理則讓系統默認的異常處理器來處理
			defalutHandler.uncaughtException(thread, ex);

		} else {
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				Log.e(TAG, "error : ", e);
			}
			// 退出程序
			android.os.Process.killProcess(android.os.Process.myPid());
			System.exit(1);
		}
	}

	/**
	 * 自定義錯誤處理,收集錯誤信息 發送錯誤報告等操作均在此完成.
	 * 
	 * @param ex
	 * @return true:如果處理了該異常信息;否則返回false.
	 */
	private boolean handleException(final Throwable ex) {
		if (ex == null) {
			return false;
		}

		new Thread() {

			@Override
			public void run() {
				Looper.prepare();

				ex.printStackTrace();
				String err = "[" + ex.getMessage() + "]";
				Toast.makeText(context, "程序出現異常." + err, Toast.LENGTH_LONG)
						.show();

				Looper.loop();
			}

		}.start();

		// 收集設備參數信息 \日誌信息
		String errInfo = collectDeviceInfo(context, ex);
		// 保存日誌文件
		saveCrashInfo2File(errInfo);
		return true;                                                                                                                }
}

2、應用綁定異常處理方法:

在Application或者Activity的onCreate方法中加入以下兩句調用即可:

<span style="font-family:Courier New;">CrashHandler crashHandler = CrashHandler.getInstance();
crashHandler.init(getApplicationContext());</span>


發佈了91 篇原創文章 · 獲贊 18 · 訪問量 56萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章