android 捕獲全局異常;

本身定義一個用於捕獲全局異常的類,繼承自 Thread.UncaughtException:java

  1. 給此類(CrashHandler)設計一個單例:
    android

  2. 繼承UncaughtException後實現   uncaughtException(Thread thread, Throwable ex) 方法服務器

  3. 自定義抓取異常的處理操做: handleException(Throwable ex)
    app


代碼以下:ide

public class CrashHandler implements Thread.UncaughtExceptionHandler {

    private static final String TAG = "CrashHandler";
    private Thread.UncaughtExceptionHandler defaultHandler;
    private Context context;
    private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");

    //用來存儲設備信息和異常信息
    private Map<String, String> infos = new HashMap<String, String>();

    //建立CrashHandler實例(單例模式);
    private static CrashHandler instance = new CrashHandler();

    public static CrashHandler getInstance() {
        return instance;
    }

    /**
     * 私有化構造器保證只有一個對象
     */
    private CrashHandler() {

    }

    
    
    /**
     * 初始化
     *
     * @param context
     */
    public void init(Context context) {

        this.context = context;

        //獲取系統默認的uncaughtException處理器
        defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        //設置crashhandler爲程序默認的處理器
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    

    /**
     * 當UncaughtException發生時會轉入該函數來處理
     *
     * @param thread
     * @param ex
     */
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if (!handleException(ex) && defaultHandler != null) {
            //若是用戶沒有處理則讓系統默認的異常處理器來處理
            defaultHandler.uncaughtException(thread, ex);
        }else {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                Log.e(TAG, "uncaughtException: error",e );
            }

            //退出程序
            Process.killProcess(0);
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(1);//非正常退出;
        }
    }



    /**
     * 自定義錯誤處理,手機錯誤信息,發送錯誤拔高等操做均在此完成
     *
     * @param ex
     * @return true; 若是處理了該異常信息; 不然返回false
     */
    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }
        //使用Toast來顯示異常信息
        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                Toast.makeText(context, "很抱歉,程序出現異常,即將退出", Toast.LENGTH_SHORT).show();
                Looper.loop();
            }
        }.start();

        //手機設備參數信息;
        collectDeviceInfo(context);

        //保存日誌文件:
        saveCrashInfo2File(ex);
        return true;
    }
    
    
    
    /**
     * 保存錯誤信息到文件中
     * @param ex
     * @return 返回文件名稱,便於將文件傳送到服務器
     */
    private String saveCrashInfo2File(Throwable ex) {
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> entry : infos.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            sb.append(key + "=" + value + "\n");
        }

        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();

        String result = writer.toString();
        sb.append(result);

        String fileName = null;
        try {
            long timestamp = System.currentTimeMillis();
            String time = dateFormat.format(new Date());
            fileName = "crash-" + time + "-" + timestamp + ".loge";
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                String path = "/sdcard/crash/";
                File dir = new File(path);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                FileOutputStream fos = new FileOutputStream(path + fileName);
                fos.write(sb.toString().getBytes());
                fos.close();
            }
            return fileName;
        } catch (IOException e) {
            Log.e(TAG, "saveCrashInfo2File: an error occured while writing file", e);
        }

        return null;
    }

    
    
    
    /**
     * 手機設備參數信息
     *
     * @param context
     */
    private void collectDeviceInfo(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_ACTIVITIES);

            if (packageInfo != null) {
                String versinName = packageInfo.versionName == null ? "null" : packageInfo.versionName;
                String versionCode = packageInfo.versionCode + "";
                infos.put("versionName", versinName);
                infos.put("versionCode", versionCode);
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, "an error occored when collect package info", e);
        }

        Field[] declaredFields = Build.class.getDeclaredFields();
        for (Field field : declaredFields) {
            try {
                field.setAccessible(true);
                infos.put(field.getName(), field.get(null).toString());
                Log.d(TAG, field.getName() + ":" + field.get(null));
            } catch (IllegalAccessException e) {
                Log.e(TAG, "collectDeviceInfo: an error occured when collect crash info", e);
            }
        }
    }
}


固然不要忘了在Application裏面初始化:函數

App Application {
    onCreate() {
        .onCreate();
        CrashHandler crashHandler = CrashHandler.();
        crashHandler.init(getApplicationContext());
    }
}

記得在menifest.xml給App添加 name
oop

文章轉自 http://blog.csdn.net/jdsjlzx/article/details/7606423
ui

相關文章
相關標籤/搜索