Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

詳解 Android 全局異常的捕獲處理

編輯:關於 Android 程式設計

在 Android 開發中,程式崩潰(crash)在所難免。當使用者隨意操作觸發了測試時未發現的 Bug 導致崩潰時,我們往往無法直接取得錯誤日誌,也就難以及時修復,這會嚴重影響使用者體驗。

為了解決這個問題,我們可以註冊一個全局異常捕獲機制:當程式崩潰時,把錯誤日誌記錄下來並上傳到伺服器,以便後續排查與修復。實現這一功能要依賴 Thread.UncaughtExceptionHandler 這個介面,它位於 Thread 中,只有一個方法 uncaughtException。當我們註冊它之後,程式一旦崩潰就會回呼該方法,並透過參數把崩潰資訊傳入。

 package hi.xiaoyu.crashhandler; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.lang.Thread.UncaughtExceptionHandler; import java.util.Date; import android.content.Context; import android.os.Environment; import android.util.Log; public class CrashHandler implements UncaughtExceptionHandler { private static CrashHandler instance; public static CrashHandler getInstance() { if (instance == null) { instance = new CrashHandler(); } return instance; } public void init(Context ctx) { Thread.setDefaultUncaughtExceptionHandler(this); } /** * 核心方法,當程序crash 會回調此方法, Throwable中存放這錯誤日志 */ @Override public void uncaughtException(Thread arg0, Throwable arg1) { String logPath; if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { logPath = Environment.getExternalStorageDirectory() .getAbsolutePath() + File.separator + File.separator + "log"; File file = new File(logPath); if (!file.exists()) { file.mkdirs(); } try { FileWriter fw = new FileWriter(logPath + File.separator + "errorlog.log", true); fw.write(new Date() + "\n"); // 錯誤信息 // 這裡還可以加上當前的系統版本,機型型號 等等信息 StackTraceElement[] stackTrace = arg1.getStackTrace(); fw.write(arg1.getMessage() + "\n"); for (int i = 0; i < stackTrace.length; i++) { fw.write("file:" + stackTrace[i].getFileName() + " class:" + stackTrace[i].getClassName() + " method:" + stackTrace[i].getMethodName() + " line:" + stackTrace[i].getLineNumber() + "\n"); } fw.write("\n"); fw.close(); // 上傳錯誤信息到服務器 // uploadToServer(); } catch (IOException e) { Log.e("crash handler", "load file failed...", e.getCause()); } } arg1.printStackTrace(); android.os.Process.killProcess(android.os.Process.myPid()); } } 

完成後,只要在 Activity 或 Application 中註冊一下即可:

 CrashHandler crashHandler = CrashHandler.getInstance(); crashHandler.init(getApplicationContext()); 

如此一來,就實現了 Android 全局異常的捕獲與處理。實現過程並不複雜,卻能極大提升線上問題的可維護性,希望對大家學習 Android 軟體編程有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved