校園助手APP–昨天看代碼發現了一個好東西——UncaughtExceptionHandler

分類:編程 時間:2017-04-03

昨天看以前寫的代碼,發現了一個特別nice的東西UncaughtExceptionHandler,貼上代碼看看:

/** 
 * UncaughtExceptionHandler:線程未捕獲異常控制器是用來處理未捕獲異常的。  
 *                           如果程序出現了未捕獲異常默認情況下則會出現強行關閉對話框 
 *                           實現該接口並註冊為程序中的默認未捕獲異常處理  
 *                           這樣當未捕獲異常發生時,就可以做些異常處理操作 
 *                           例如:收集異常信息,發送錯誤報告 等。 
 *  
 * UncaughtException處理類,當程序發生Uncaught異常的時候,由該類來接管程序,並記錄發送錯誤報告. 
 */  
public class CrashHandler implements UncaughtExceptionHandler {  
    /** Debug Log Tag */  
    public static final String TAG = "CrashHandler";  
    /** 是否開啟日誌輸出, 在Debug狀態下開啟, 在Release狀態下關閉以提升程序性能 */  
    public static final boolean DEBUG = true;  
    /** CrashHandler實例 */  
    private static CrashHandler INSTANCE;  
    /** 程序的Context對象 */  
    private Context mContext;  
    /** 系統默認的UncaughtException處理類 */  
    private Thread.UncaughtExceptionHandler mDefaultHandler;  
      
    /** 使用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 exception) {  
        
    	if (!handleException(exception) && mDefaultHandler != null) {  
            // 如果用戶沒有處理則讓系統默認的異常處理器來處理  
            mDefaultHandler.uncaughtException(thread, exception);  
        } else {  
            // Sleep一會後結束程序  
            // 來讓線程停止一會是為了顯示Toast信息給用戶,然後Kill程序  
            try {  
                Thread.sleep(3000);  
            } 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 exception) {  
        
    	if (exception == null) {  
            return true;  
        }  
        final String msg = exception.getLocalizedmessage();  
        // 使用Toast來顯示異常信息  
        new Thread() {  
            @Override  
            public void run() {  
                // Toast 顯示需要出現在一個線程的消息隊列中  
                Looper.prepare();  
                Toast.makeText(mContext, "程序出錯啦:" + msg, Toast.LENGTH_LONG).show();  
                Looper.loop();  
            }  
        }.start();  
        // 收集設備信息  
        collectCrashDeviceInfo(mContext);  
        // 保存錯誤報告文件  
        String crashFileName = saveCrashInfoToFile(exception);  
        
        System.out.println(crashFileName);
        // 發送錯誤報告到服務器  
        sendCrashReportsToServer(mContext);  
        return true;  
    }  
  
    /** 
     * 收集程序崩潰的設備信息 
     *  
     * @param ctx 
     */  
    public void collectCrashDeviceInfo(Context context) {  
        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 = context.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(context.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, pi.versionCode);  
            }  
        } catch (NameNotFoundException e) {  
            Log.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(), 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);  
            }  
        }  
    }  
      
    /** 
     * 保存錯誤信息到文件中 
     *  
     * @param ex 
     * @return 
     */  
    private String saveCrashInfoToFile(Throwable exception) {  
    	
        Writer info = new StringWriter();  
        PrintWriter printWriter = new PrintWriter(info);  
        // printStackTrace(PrintWriter s)  
        // 將此 throwable 及其追蹤輸出到指定的 PrintWriter  
        exception.printStackTrace(printWriter);  
  
        // getCause() 返回此 throwable 的 cause;如果 cause 不存在或未知,則返回 null。  
        Throwable cause = exception.getCause();  
        while (cause != null) {  
            cause.printStackTrace(printWriter);  
            cause = cause.getCause();  
        }  
  
        // toString() 以字符串的形式返回該緩沖區的當前值。  
        String result = info.toString();  
        printWriter.close();  
        mDeviceCrashInfo.put(STACK_TRACE, result);  
  
        try {  
            long timestamp = System.currentTimeMillis();  
            String fileName = "crash-" + timestamp + 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 
     */  
    private void sendCrashReportsToServer(Context context) {  
        String[] crFiles = getCrashReportFiles(context);  
        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(context.getFilesDir(), fileName);  
                if (postReport(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 boolean postReport(File file) {  
        //  使用HTTP Post 發送錯誤報告到服務器  
        // 這裏不再詳述,開發者可以根據OPhoneSDN上的其他網絡操作  
        // 教程來提交錯誤報告  
    	return false;
    }  
  
    /** 
     * 在程序啟動時候, 可以調用該函數來發送以前沒有發送的報告 
     */  
    public void sendPreviousReportsToServer() {  
        sendCrashReportsToServer(mContext);  
    }  
}  

竟然還用到了Application,溫故而知新啊,哈哈哈

public class MyApplication extends Application{

    @Override  
    public void onCreate() {  
        super.onCreate();  
        CrashHandler crashHandler = CrashHandler.getInstance();  
        // 註冊crashHandler  
        crashHandler.init(getApplicationContext());  
        // 發送以前沒發送的報告(可選)  
        crashHandler.sendPreviousReportsToServer();  
    }  
	
}

Tags: private public 控制器 對話框 校園

文章來源:


ads
ads

相關文章
ads

相關文章

ad