在SDCard中用文件記錄android的異常信息

  1. 以下爲異常捕捉處理代碼:  
  1. import java.io.BufferedReader;  
  2. import java.io.File;  
  3. import java.io.FileInputStream;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7. import java.io.InputStreamReader;  
  8. import java.io.PrintWriter;  
  9. import java.io.StringWriter;  
  10. import java.io.Writer;  
  11. import java.lang.Thread.UncaughtExceptionHandler;  
  12. import java.lang.reflect.Field;  
  13. import java.text.DateFormat;  
  14. import java.text.SimpleDateFormat;  
  15. import java.util.Date;  
  16. import java.util.HashMap;  
  17. import java.util.Map;  
  18.   
  19. import android.content.Context;  
  20. import android.content.pm.PackageInfo;  
  21. import android.content.pm.PackageManager;  
  22. import android.content.pm.PackageManager.NameNotFoundException;  
  23. import android.os.Build;  
  24. import android.os.Environment;  
  25. import android.os.Looper;  
  26. import android.util.Log;  
  27. import android.widget.Toast;  
  28.       
  29. /**   
  30.  * UncaughtException處理類,當程序發生Uncaught異常的時候,有該類來接管程序,並記錄發送錯誤報告.  
  31.  *  
  32.  *  需要在Application中註冊,爲了要在程序啓動器就監控整個程序。 
  33.  */      
  34. public class CrashHandler implements UncaughtExceptionHandler {      
  35.           
  36.     public static final String TAG = "CrashHandler";      
  37.           
  38.     //系統默認的UncaughtException處理類       
  39.     private Thread.UncaughtExceptionHandler mDefaultHandler;      
  40.     //CrashHandler實例      
  41.     private static CrashHandler instance;  
  42.    //程序的Context對象      
  43.     private Context mContext;      
  44.     //用來存儲設備信息和異常信息      
  45.     private Map<String, String> infos = new HashMap<String, String>();      
  46.       
  47.     //用於格式化日期,作爲日誌文件名的一部分      
  48.     private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");      
  49.       
  50.     /** 保證只有一個CrashHandler實例 */      
  51.     private CrashHandler() {}      
  52.       
  53.     /** 獲取CrashHandler實例 ,單例模式 */      
  54.     public static CrashHandler getInstance() {      
  55.         if(instance == null)  
  56.             instance = new CrashHandler();     
  57.         return instance;      
  58.     }      
  59.       
  60.     /**   
  61.      * 初始化   
  62.      */      
  63.     public void init(Context context) {      
  64.         mContext = context;      
  65.         //獲取系統默認的UncaughtException處理器      
  66.         mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();      
  67.         //設置該CrashHandler爲程序的默認處理器      
  68.         Thread.setDefaultUncaughtExceptionHandler(this);      
  69.     }      
  70.       
  71.     /**   
  72.      * 當UncaughtException發生時會轉入該函數來處理   
  73.      */      
  74.     @Override      
  75.     public void uncaughtException(Thread thread, Throwable ex) {      
  76.         if (!handleException(ex) && mDefaultHandler != null) {      
  77.             //如果用戶沒有處理則讓系統默認的異常處理器來處理      
  78.             mDefaultHandler.uncaughtException(thread, ex);      
  79.         } else {      
  80.             try {      
  81.                 Thread.sleep(3000);      
  82.             } catch (InterruptedException e) {      
  83.                 Log.e(TAG, "error : ", e);      
  84.             }      
  85.             //退出程序      
  86.             android.os.Process.killProcess(android.os.Process.myPid());      
  87.             System.exit(1);      
  88.         }      
  89.     }      
  90.       
  91.     /**   
  92.      * 自定義錯誤處理,收集錯誤信息 發送錯誤報告等操作均在此完成.   
  93.      *    
  94.      * @param ex   
  95.      * @return true:如果處理了該異常信息;否則返回false.   
  96.      */      
  97.     private boolean handleException(Throwable ex) {      
  98.         if (ex == null) {      
  99.             return false;      
  100.         }      
  101.         //收集設備參數信息       
  102.         collectDeviceInfo(mContext);      
  103.           
  104.         //使用Toast來顯示異常信息      
  105.         new Thread() {      
  106.             @Override      
  107.             public void run() {      
  108.                 Looper.prepare();      
  109.                 Toast.makeText(mContext, "很抱歉,程序出現異常,即將退出.", Toast.LENGTH_SHORT).show();      
  110.                 Looper.loop();      
  111.             }      
  112.         }.start();      
  113.         //保存日誌文件       
  114.         saveCatchInfo2File(ex);    
  115.         return true;      
  116.     }      
  117.           
  118.     /**   
  119.      * 收集設備參數信息   
  120.      * @param ctx   
  121.      */      
  122.     public void collectDeviceInfo(Context ctx) {      
  123.         try {      
  124.             PackageManager pm = ctx.getPackageManager();      
  125.             PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);      
  126.             if (pi != null) {      
  127.                 String versionName = pi.versionName == null ? "null" : pi.versionName;      
  128.                 String versionCode = pi.versionCode + "";      
  129.                 infos.put("versionName", versionName);      
  130.                 infos.put("versionCode", versionCode);      
  131.             }      
  132.         } catch (NameNotFoundException e) {      
  133.             Log.e(TAG, "an error occured when collect package info", e);      
  134.         }      
  135.         Field[] fields = Build.class.getDeclaredFields();      
  136.         for (Field field : fields) {      
  137.             try {      
  138.                 field.setAccessible(true);      
  139.                 infos.put(field.getName(), field.get(null).toString());      
  140.                 Log.d(TAG, field.getName() + " : " + field.get(null));      
  141.             } catch (Exception e) {      
  142.                 Log.e(TAG, "an error occured when collect crash info", e);      
  143.             }      
  144.         }      
  145.     }      
  146.       
  147.     /**   
  148.      * 保存錯誤信息到文件中   
  149.      *    
  150.      * @param ex   
  151.      * @return  返回文件名稱,便於將文件傳送到服務器   
  152.      */      
  153.     private String saveCatchInfo2File(Throwable ex) {      
  154.               
  155.         StringBuffer sb = new StringBuffer();      
  156.         for (Map.Entry<String, String> entry : infos.entrySet()) {      
  157.             String key = entry.getKey();      
  158.             String value = entry.getValue();      
  159.             sb.append(key + "=" + value + "\n");      
  160.         }      
  161.               
  162.         Writer writer = new StringWriter();      
  163.         PrintWriter printWriter = new PrintWriter(writer);      
  164.         ex.printStackTrace(printWriter);      
  165.         Throwable cause = ex.getCause();      
  166.         while (cause != null) {      
  167.             cause.printStackTrace(printWriter);      
  168.             cause = cause.getCause();      
  169.         }      
  170.         printWriter.close();      
  171.         String result = writer.toString();      
  172.         sb.append(result);      
  173.         try {      
  174.             long timestamp = System.currentTimeMillis();      
  175.             String time = formatter.format(new Date());      
  176.             String fileName = "crash-" + time + "-" + timestamp + ".log";      
  177.             if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {      
  178.                 String path = "/mnt/sdcard/crash/";      
  179.                 File dir = new File(path);      
  180.                 if (!dir.exists()) {      
  181.                     dir.mkdirs();      
  182.                 }      
  183.                 FileOutputStream fos = new FileOutputStream(path + fileName);      
  184.                 fos.write(sb.toString().getBytes());    
  185.                 //發送給開發人員  
  186.                 sendCrashLog2PM(path+fileName);  
  187.                 fos.close();      
  188.             }      
  189.             return fileName;      
  190.         } catch (Exception e) {      
  191.             Log.e(TAG, "an error occured while writing file...", e);      
  192.         }      
  193.         return null;      
  194.     }      
  195.       
  196.     /** 
  197.      * 將捕獲的導致崩潰的錯誤信息發送給開發人員 
  198.      *  
  199.      * 目前只將log日誌保存在sdcard 和輸出到LogCat中,並未發送給後臺。 
  200.      */  
  201.     private void sendCrashLog2PM(String fileName){  
  202.         if(!new File(fileName).exists()){  
  203.             Toast.makeText(mContext, "日誌文件不存在!", Toast.LENGTH_SHORT).show();  
  204.             return;  
  205.         }  
  206.         FileInputStream fis = null;  
  207.         BufferedReader reader = null;  
  208.         String s = null;  
  209.         try {  
  210.             fis = new FileInputStream(fileName);  
  211.             reader = new BufferedReader(new InputStreamReader(fis, "GBK"));  
  212.             while(true){  
  213.                 s = reader.readLine();  
  214.                 if(s == nullbreak;  
  215.                 //由於目前尚未確定以何種方式發送,所以先打出log日誌。  
  216.                 Log.i("info", s.toString());  
  217.             }  
  218.         } catch (FileNotFoundException e) {  
  219.             e.printStackTrace();  
  220.         } catch (IOException e) {  
  221.             e.printStackTrace();  
  222.         }finally{   // 關閉流  
  223.             try {  
  224.                 reader.close();  
  225.                 fis.close();  
  226.             } catch (IOException e) {  
  227.                 e.printStackTrace();  
  228.             }  
  229.         }  
  230.     }  
  231. }      


針對異常的捕捉要進行全局監控整個項目,所以要將其在Application中註冊(也就是初始化):

  1. import android.app.Application;  
  2.   
  3. public class CrashApplication extends Application {  
  4.   
  5.     @Override  
  6.     public void onCreate() {  
  7.         super.onCreate();  
  8.         CrashHandler catchHandler = CrashHandler.getInstance();  
  9.         catchHandler.init(getApplicationContext());  
  10.     }  
  11. }  

現在模擬一個空指針異常:

  1. import android.app.Activity;  
  2. import android.os.Bundle;  
  3.   
  4. public class CatchExceptionLogActivity extends Activity {  
  5.     /** Called when the activity is first created. */  
  6.     private String s;  
  7.     @Override  
  8.     public void onCreate(Bundle savedInstanceState) {  
  9.         super.onCreate(savedInstanceState);  
  10.         setContentView(R.layout.main);  
  11.         System.out.println(s.equals("hello"));  // s沒有進行賦值,所以會出現NullPointException異常  
  12.     }  
  13. }  

別忘了在配置文件中對Application進行註冊:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.forms.catchlog"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.   
  7.     <uses-sdk android:minSdkVersion="8" />  
  8.     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
  9.       
  10.   
  11.     <application  
  12.         android:icon="@drawable/ic_launcher"  
  13.         android:label="@string/app_name"   
  14.         <span style="color:#ff0000;">android:name=".CrashApplication"></span>  
  15.         <activity  
  16.             android:label="@string/app_name"  
  17.             android:name=".CatchExceptionLogActivity" >  
  18.             <intent-filter >  
  19.                 <action android:name="android.intent.action.MAIN" />  
  20.   
  21.                 <category android:name="android.intent.category.LAUNCHER" />  
  22.             </intent-filter>  
  23.         </activity>  
  24.     </application>  
  25.   
  26. </manifest>  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章