- package qianlong.qlmobile.ui;
- import java.io.File;
- 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 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.text.format.Time;
- import android.util.Log;
- import android.view.Gravity;
- import android.widget.Toast;
- public class CrashHandler implements UncaughtExceptionHandler {
- /** Debug Log tag*/
- public static final String TAG = "CrashHandler";
- /** 是否開啓日誌輸出,在Debug狀態下開啓,
- * 在Release狀態下關閉以提示程序性能
- * */
- public static final boolean DEBUG = false;
- /** 系統默認的UncaughtException處理類 */
- private Thread.UncaughtExceptionHandler mDefaultHandler;
- /** CrashHandler實例 */
- private static CrashHandler INSTANCE;
- /** 程序的Context對象 */
- private Context mContext;
- /** 使用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一會後結束程序
- try {
- Thread.sleep(5000);
- } catch (InterruptedException e) {
- Log.e(TAG, "Error : ", e);
- }
- android.os.Process.killProcess(android.os.Process.myPid());
- System.exit(10);
- }
- }
- /**
- * 自定義錯誤處理,收集錯誤信息
- * 發送錯誤報告等操作均在此完成.
- * 開發者可以根據自己的情況來自定義異常處理邏輯
- * @param ex
- * @return true:如果處理了該異常信息;否則返回false
- */
- private boolean handleException(Throwable ex) {
- if (ex == null) {
- Log.w(TAG, "handleException --- ex==null");
- return true;
- }
- final String msg = ex.getLocalizedMessage();
- if(msg == null) {
- return false;
- }
- //使用Toast來顯示異常信息
- new Thread() {
- @Override
- public void run() {
- Looper.prepare();
- Toast toast = Toast.makeText(mContext, "程序出錯,即將退出:\r\n" + msg,
- Toast.LENGTH_LONG);
- toast.setGravity(Gravity.CENTER, 0, 0);
- toast.show();
- // MsgPrompt.showMsg(mContext, "程序出錯啦", msg+"\n點確認退出");
- Looper.loop();
- }
- }.start();
- //收集設備信息
- collectCrashDeviceInfo(mContext);
- //保存錯誤報告文件
- saveCrashInfoToFile(ex);
- //發送錯誤報告到服務器
- //sendCrashReportsToServer(mContext);
- return true;
- }
- /**
- * 在程序啓動時候, 可以調用該函數來發送以前沒有發送的報告
- */
- public void sendPreviousReportsToServer() {
- sendCrashReportsToServer(mContext);
- }
- /**
- * 把錯誤報告發送給服務器,包含新產生的和以前沒發送的.
- * @param ctx
- */
- private 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(cr);
- cr.delete();// 刪除已發送的報告
- }
- }
- }
- private void postReport(File file) {
- // TODO 發送錯誤報告到服務器
- }
- /**
- * 獲取錯誤報告文件名
- * @param ctx
- * @return
- */
- private String[] getCrashReportFiles(Context ctx) {
- File filesDir = ctx.getFilesDir();
- FilenameFilter filter = new FilenameFilter() {
- public boolean accept(File dir, String name) {
- return name.endsWith(CRASH_REPORTER_EXTENSION);
- }
- };
- return filesDir.list(filter);
- }
- /**
- * 保存錯誤信息到文件中
- * @param ex
- * @return
- */
- private String saveCrashInfoToFile(Throwable ex) {
- Writer info = new StringWriter();
- PrintWriter printWriter = new PrintWriter(info);
- ex.printStackTrace(printWriter);
- Throwable cause = ex.getCause();
- while (cause != null) {
- cause.printStackTrace(printWriter);
- cause = cause.getCause();
- }
- String result = info.toString();
- printWriter.close();
- mDeviceCrashInfo.put("EXEPTION", ex.getLocalizedMessage());
- mDeviceCrashInfo.put(STACK_TRACE, result);
- try {
- //long timestamp = System.currentTimeMillis();
- Time t = new Time("GMT+8");
- t.setToNow(); // 取得系統時間
- int date = t.year * 10000 + t.month * 100 + t.monthDay;
- int time = t.hour * 10000 + t.minute * 100 + t.second;
- String fileName = "crash-" + date + "-" + time + CRASH_REPORTER_EXTENSION;
- FileOutputStream trace = mContext.openFileOutput(fileName,
- Context.MODE_PRIVATE);
- mDeviceCrashInfo.store(trace, "");
- trace.flush();
- trace.close();
- return fileName;
- } catch (Exception e) {
- Log.e(TAG, "an error occured while writing report file...", e);
- }
- return null;
- }
- /**
- * 收集程序崩潰的設備信息
- *
- * @param ctx
- */
- public void collectCrashDeviceInfo(Context ctx) {
- try {
- PackageManager pm = ctx.getPackageManager();
- PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(),
- PackageManager.GET_ACTIVITIES);
- if (pi != null) {
- mDeviceCrashInfo.put(VERSION_NAME,
- pi.versionName == null ? "not set" : pi.versionName);
- mDeviceCrashInfo.put(VERSION_CODE, ""+pi.versionCode);
- }
- } catch (NameNotFoundException e) {
- Log.e(TAG, "Error while collect package info", e);
- }
- //使用反射來收集設備信息.在Build類中包含各種設備信息,
- //例如: 系統版本號,設備生產商 等幫助調試程序的有用信息
- //具體信息請參考後面的截圖
- Field[] fields = Build.class.getDeclaredFields();
- for (Field field : fields) {
- try {
- field.setAccessible(true);
- mDeviceCrashInfo.put(field.getName(), ""+field.get(null));
- if (DEBUG) {
- Log.d(TAG, field.getName() + " : " + field.get(null));
- }
- } catch (Exception e) {
- Log.e(TAG, "Error while collect crash info", e);
- }
- }
- }
- }
- 用法:
- //全局數據存儲
- public class App extends Application {
- private final static float HEAP_UTILIZATION = 0.75f;
- private final static int MIN_HEAP_SIZE = 6* 1024* 1024 ;
- @Override
- public void onCreate() {
- super.onCreate();
- // 異常處理,不需要處理時註釋掉這兩句即可!
- CrashHandler crashHandler = CrashHandler.getInstance();
- // 註冊crashHandler
- crashHandler.init(getApplicationContext());
- // 優化內存,以下非必須!
- VMRuntime.getRuntime().setTargetHeapUtilization(HEAP_UTILIZATION);
- VMRuntime.getRuntime().setMinimumHeapSize(MIN_HEAP_SIZE);
- //changeMetrics(this);//修改屏幕Density
- ......
- }
- }
異常時寫入文件,下面是data/data中生成的文件:
- //
- private static final boolean DebugFlag = false;
- //修改屏幕Density
- public static void changeMetrics(Context context) {
- DisplayMetrics curMetrics = context.getResources().getDisplayMetrics();
- if(!DebugFlag) {
- if (curMetrics.densityDpi == DisplayMetrics.DENSITY_HIGH) {
- DisplayMetrics metrics = new DisplayMetrics();
- metrics.scaledDensity = 1.0f;
- metrics.density = 1.0f;
- metrics.densityDpi = DisplayMetrics.DENSITY_MEDIUM;
- metrics.xdpi = DisplayMetrics.DENSITY_MEDIUM;
- metrics.ydpi = DisplayMetrics.DENSITY_MEDIUM;
- metrics.heightPixels = curMetrics.heightPixels;
- metrics.widthPixels = curMetrics.widthPixels;
- context.getResources().getDisplayMetrics().setTo(metrics);
- }
- } else {
- DisplayMetrics metrics = new DisplayMetrics();
- metrics.scaledDensity = (float)(130/160.0);
- metrics.density = (float)(130/160.0);
- metrics.densityDpi = 130;
- metrics.xdpi = 130;
- metrics.ydpi = 130;
- metrics.heightPixels = curMetrics.heightPixels;
- metrics.widthPixels = curMetrics.widthPixels;
- context.getResources().getDisplayMetrics().setTo(metrics);
- }
- }