在Android開發中在所難免的會出現程序crash,俗稱崩潰。用戶的隨意性訪問出現測試時未知的Bug導致我們的程序crash,此時我們是無法直接獲取的錯誤log的,也就無法修復Bug。這就會極大的影響用戶體驗,此時我們需要注冊一個功能來捕獲全局的異常信息,當程序出現crash信息,我們把錯誤log記錄下來,上傳到服務器,以便于我們能及時修復bug。實現這個功能我們需要依賴于UncaughtExceptionHandler這個類,UncaughtExceptionHandler是一個接口,在Thread中。里面只有一個方法uncaughtException。當我們注冊一個UncaughtExceptionHandler之后,當我們的程序crash時就會回調uncaughtException方法,而uncaughtException方法帶有兩個參數,參數中就存放這crash信息。接下來只看寫代碼
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軟件編程有所幫助。
新聞熱點
疑難解答
圖片精選