當我們做android用戶端產品的時候為了讓使用者有更好的體驗,我們需要攔截系統的異常彈出事件,並且將這些異常以比較“優雅”的方式反饋給使用者,當然我們還要把這些異常提交到伺服器上以便於程式員分析產生這些異常的原因,更好的維護和晚上這個android用戶端產品.
首先在我們的application的oncreat()方法加入以下代碼:
MobclickAgent.onError(context); CrashHandler crashHandler = CrashHandler.getInstance(); // 註冊crashHandler crashHandler.init(getApplicationContext());
接著我們看crashHandler類:需要注意的一點是這裡採用了友盟的sdk來上傳異常資訊,至於友盟怎麼用:http://www.umeng.com/
import java.io.File; import java.io.FileInputStream;import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.lang.Thread.UncaughtExceptionHandler; import java.lang.reflect.Field; import java.util.Arrays; import java.util.Properties; import java.util.TreeSet; import org.apache.http.util.EncodingUtils;import com.kaixin001.model.Setting;import com.kaixin001.util.KXLog;import com.umeng.analytics.MobclickAgent; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Build; import android.os.Looper; import android.widget.Toast; /** * * * UncaughtExceptionHandler:線程未捕獲異常控制器是用來處理未捕獲異常的。 * 如果程式出現了未捕獲異常預設情況下則會出現強行關閉對話方塊 * 實現該介面並註冊為程式中的預設未捕獲異常處理 * 這樣當未捕獲異常發生時,就可以做些異常處理操作 * 例如:收集異常資訊,發送錯誤報表 等。 * * UncaughtException處理類,當程式發生Uncaught異常的時候,由該類來接管程式,並記錄發送錯誤報表. */ public class CrashHandler implements UncaughtExceptionHandler { /** Debug Log Tag */ public static final String TAG = "CrashHandler"; /** CrashHandler執行個體 */ private static CrashHandler INSTANCE; /** 程式的Context對象 */ private Context mContext; /** 系統預設的UncaughtException處理類 */ private Thread.UncaughtExceptionHandler mDefaultHandler; private SendReports sendReports=null; /** 使用Properties來儲存裝置的資訊和錯誤堆棧資訊 */ private Properties mDeviceCrashInfo = new Properties(); private static final String VERSION_NAME = "versionName"; private static final String VERSION_CODE = "versionCode"; private static final String STACK_TRACE = "STACK_TRACE"; /** 錯誤報表檔案的副檔名 */ private static final String CRASH_REPORTER_EXTENSION = ".cr"; /** 保證只有一個CrashHandler執行個體 */ private CrashHandler() { } /** 擷取CrashHandler執行個體 ,單例模式 */ public static CrashHandler getInstance() { if (INSTANCE == null) INSTANCE = new CrashHandler(); return INSTANCE; } /** * 初始化,註冊Context對象, 擷取系統預設的UncaughtException處理器, 設定該CrashHandler為程式的預設處理器 * * @param ctx */ public void init(Context ctx) { mContext = ctx; mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler(); Thread.setDefaultUncaughtExceptionHandler(this); } /** * 當UncaughtException發生時會轉入該函數來處理 */ @Override public void uncaughtException(Thread thread, Throwable ex) { if (!handleException(ex) && mDefaultHandler != null) { // 如果使用者沒有處理則讓系統預設的異常處理器來處理 mDefaultHandler.uncaughtException(thread, ex); } else { // Sleep一會後結束程式 // 來讓線程停止一會是為了顯示Toast資訊給使用者,然後Kill程式 try { Thread.sleep(4000); } catch (InterruptedException e) { KXLog.e(TAG, "Error : ", e); } android.os.Process.killProcess(android.os.Process.myPid()); System.exit(10); } } /** * 自訂錯誤處理,收集錯誤資訊 發送錯誤報表等操作均在此完成. 開發人員可以根據自己的情況來自訂異常處理邏輯 * * @param ex * @return true:如果處理了該異常資訊;否則返回false */ private boolean handleException(final Throwable ex) { if (ex == null) { return true; } final String msg = ex.getLocalizedMessage(); // 使用Toast來顯示異常資訊 new Thread() { @Override public void run() { // Toast 顯示需要出現在一個線程的訊息佇列中 Looper.prepare(); Toast.makeText(mContext, "程式出錯啦,我們會儘快修改:" + msg, Toast.LENGTH_SHORT).show(); Looper.loop(); } }.start(); // 收集裝置資訊 collectCrashDeviceInfo(mContext); // 使用友盟SDK將錯誤報表儲存到檔案中,待下次應用程式重啟時上傳log String crashFileName = saveCrashInfoToFile(ex); // 發送錯誤報表到伺服器 //已經使用了友盟SDK上傳,故此處注掉 //sendCrashReportsToServer(mContext); return true; } /** * 收集程式崩潰的裝置資訊 * * @param ctx */ public void collectCrashDeviceInfo(Context ctx) { try { // Class for retrieving various kinds of information related to the // application packages that are currently installed on the device. // You can find this class through getPackageManager(). PackageManager pm = ctx.getPackageManager(); // getPackageInfo(String packageName, int flags) // Retrieve overall information about an application package that is installed on the system. // public static final int GET_ACTIVITIES // Since: API Level 1 PackageInfo flag: return information about activities in the package in activities. PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES); if (pi != null) { // public String versionName The version name of this package, // as specified by the <manifest> tag's versionName attribute. mDeviceCrashInfo.put(VERSION_NAME, pi.versionName == null ? "not set" : pi.versionName); // public int versionCode The version number of this package, // as specified by the <manifest> tag's versionCode attribute. mDeviceCrashInfo.put(VERSION_CODE, String.valueOf(pi.versionCode)); } //添加渠道號 mDeviceCrashInfo.put("ctype", Setting.getInstance().getCType()); } catch (NameNotFoundException e) { KXLog.e(TAG, "Error while collect package info", e); } // 使用反射來收集裝置資訊.在Build類中包含各種裝置資訊, // 例如: 系統版本號碼,裝置生產商 等協助偵錯工具的有用資訊 // 返回 Field 對象的一個數組,這些對象反映此 Class 對象所表示的類或介面所聲明的所有欄位 Field[] fields = Build.class.getDeclaredFields(); for (Field field : fields) { try { // setAccessible(boolean flag) // 將此對象的 accessible 標誌設定為指示的布爾值。 // 通過設定Accessible屬性為true,才能對私人變數進行訪問,不然會得到一個IllegalAccessException的異常 field.setAccessible(true); mDeviceCrashInfo.put(field.getName(), String.valueOf(field.get(null))); KXLog.d(TAG, field.getName() + " : " + field.get(null)); } catch (Exception e) { KXLog.e(TAG, "Error while collect crash info", e); } } } /** * 儲存錯誤資訊到檔案中 * * @param ex * @return */ private String saveCrashInfoToFile(Throwable ex) { Writer info = new StringWriter(); PrintWriter printWriter = new PrintWriter(info); // printStackTrace(PrintWriter s) // 將此 throwable 及其追蹤輸出到指定的 PrintWriter ex.printStackTrace(printWriter); // getCause() 返回此 throwable 的 cause;如果 cause 不存在或未知,則返回 null。 Throwable cause = ex.getCause(); while (cause != null) { cause.printStackTrace(printWriter); cause = cause.getCause(); } // toString() 以字串的形式返回該緩衝區的當前值。 String result = info.toString(); printWriter.close(); mDeviceCrashInfo.put(STACK_TRACE, result); KXLog.e(TAG, result); //友盟是現將錯誤資訊儲存在com_umeng__crash.cache檔案中,然後在應用程式啟動時調用MobclickAgent.onError(context);來啟動一線程上傳log String log=mDeviceCrashInfo.toString(); MobclickAgent.reportError(mContext,log); return null; } /** * 把錯誤報表發送給伺服器,包含新產生的和以前沒發送的. * * @param ctx */ public void sendCrashReportsToServer(Context ctx) { String[] crFiles = getCrashReportFiles(ctx); if (crFiles != null && crFiles.length > 0) { TreeSet<String> sortedFiles = new TreeSet<String>(); sortedFiles.addAll(Arrays.asList(crFiles)); for (String fileName : sortedFiles) { File cr = new File(ctx.getFilesDir(), fileName); postReport(ctx,cr); cr.delete();// 刪除已發送的報告 } } } /** * 擷取錯誤報表檔案名稱 * * @param ctx * @return */ private String[] getCrashReportFiles(Context ctx) { File filesDir = ctx.getFilesDir(); // 實現FilenameFilter介面的類執行個體可用於過濾器檔案名稱 FilenameFilter filter = new FilenameFilter() { // accept(File dir, String name) // 測試指定檔案是否應該包含在某一檔案清單中。 public boolean accept(File dir, String name) { return name.endsWith(CRASH_REPORTER_EXTENSION); } }; // list(FilenameFilter filter) // 返回一個字串數組,這些字串指定此抽象路徑名表示的目錄中滿足指定過濾器的檔案和目錄 return filesDir.list(filter); } private void postReport(Context ctx,File file) { try{ FileInputStream fin = new FileInputStream(file); StringBuffer localStringBuffer = new StringBuffer(); byte [] buffer = new byte[1024]; int i = 0; while ((i = fin.read(buffer)) != -1){ localStringBuffer.append(new String(buffer, 0, i)); } fin.close(); MobclickAgent.reportError(ctx,localStringBuffer.toString()); }catch(Exception e){ e.printStackTrace(); } } /** * 在程式啟動時候, 可以調用該函數來發送以前沒有發送的報告 */ public void sendPreviousReportsToServer() { if(null!=sendReports&&!sendReports.isAlive()){ sendReports.start(); } } private final class SendReports extends Thread{ private Context mContext; private final Object lock = new Object(); public SendReports(Context mContext) {this.mContext=mContext;}public void run(){try{synchronized (this.lock){sendCrashReportsToServer(mContext);}}catch(Exception e){KXLog.e(TAG, "SendReports error.",e);}} }}