Android將程序崩潰信息保存本地文件

轉載:http://blog.csdn.net/way_ping_li/article/details/7927273

大家都知道,現在安裝Android系統的手機版本和設備千差萬別,在模擬器上運行良好的程序安裝到某款手機上說不定就出現崩潰的現象,開發者個人不可能購買所有設備逐個調試,所以在程序發佈出去之後,如果出現了崩潰現象,開發者應該及時獲取在該設備上導致崩潰的信息,這對於下一個版本的bug修復幫助極大,所以今天就來介紹一下如何在程序崩潰的情況下收集相關的設備參數信息和具體的異常信息,併發送這些信息到服務器供開發者分析和調試程序。

 

源碼下載地址http://download.csdn.net/detail/weidi1989/4588310

 

我們先建立一個crash項目,項目結構如圖:

 

在MainActivity.java代碼中,故意製作一個錯誤的例子,以便於我們實驗:

[java] view plaincopy
  1. package com.scott.crash;  
  2.   
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5.   
  6. public class MainActivity extends Activity {  
  7.   
  8.     private String s;  
  9.       
  10.     @Override  
  11.     public void onCreate(Bundle savedInstanceState) {  
  12.         super.onCreate(savedInstanceState);  
  13.         System.out.println(s.equals("any string"));  
  14.     }  
  15. }  

我們在這裏故意製造了一個潛在的運行期異常,當我們運行程序時就會出現以下界面:

遇到軟件沒有捕獲的異常之後,系統會彈出這個默認的強制關閉對話框。

我們當然不希望用戶看到這種現象,簡直是對用戶心靈上的打擊,而且對我們的bug的修復也是毫無幫助的。我們需要的是軟件有一個全局的異常捕獲器,當出現一個我們沒有發現的異常時,捕獲這個異常,並且將異常信息記錄下來,上傳到服務器公開發這分析出現異常的具體原因。

接下來我們就來實現這一機制,不過首先我們還是來了解以下兩個類:android.app.Application和java.lang.Thread.UncaughtExceptionHandler。

Application:用來管理應用程序的全局狀態。在應用程序啓動時Application會首先創建,然後纔會根據情況(Intent)來啓動相應的Activity和Service。本示例中將在自定義加強版的Application中註冊未捕獲異常處理器。

Thread.UncaughtExceptionHandler:線程未捕獲異常處理器,用來處理未捕獲異常。如果程序出現了未捕獲異常,默認會彈出系統中強制關閉對話框。我們需要實現此接口,並註冊爲程序中默認未捕獲異常處理。這樣當未捕獲異常發生時,就可以做一些個性化的異常處理操作。

大家剛纔在項目的結構圖中看到的CrashHandler.java實現了Thread.UncaughtExceptionHandler,使我們用來處理未捕獲異常的主要成員,代碼如下:

[java] view plaincopy
  1. package com.way.crash;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7. import java.io.PrintWriter;  
  8. import java.io.StringWriter;  
  9. import java.io.Writer;  
  10. import java.lang.Thread.UncaughtExceptionHandler;  
  11. import java.lang.reflect.Field;  
  12. import java.text.SimpleDateFormat;  
  13. import java.util.Date;  
  14. import java.util.HashMap;  
  15. import java.util.Map;  
  16.   
  17. import android.content.Context;  
  18. import android.content.pm.PackageInfo;  
  19. import android.content.pm.PackageManager;  
  20. import android.content.pm.PackageManager.NameNotFoundException;  
  21. import android.os.Build;  
  22. import android.os.Environment;  
  23. import android.os.Looper;  
  24. import android.util.Log;  
  25. import android.widget.Toast;  
  26.   
  27. /** 
  28.  * UncaughtException處理類,當程序發生Uncaught異常的時候,由該類來接管程序,並記錄發送錯誤報告. 
  29.  *  
  30.  * @author way 
  31.  *  
  32.  */  
  33. public class CrashHandler implements UncaughtExceptionHandler {  
  34.     private static final String TAG = "CrashHandler";  
  35.     private Thread.UncaughtExceptionHandler mDefaultHandler;// 系統默認的UncaughtException處理類  
  36.     private static CrashHandler INSTANCE = new CrashHandler();// CrashHandler實例  
  37.     private Context mContext;// 程序的Context對象  
  38.     private Map<String, String> info = new HashMap<String, String>();// 用來存儲設備信息和異常信息  
  39.     private SimpleDateFormat format = new SimpleDateFormat(  
  40.             "yyyy-MM-dd-HH-mm-ss");// 用於格式化日期,作爲日誌文件名的一部分  
  41.   
  42.     /** 保證只有一個CrashHandler實例 */  
  43.     private CrashHandler() {  
  44.   
  45.     }  
  46.   
  47.     /** 獲取CrashHandler實例 ,單例模式 */  
  48.     public static CrashHandler getInstance() {  
  49.         return INSTANCE;  
  50.     }  
  51.   
  52.     /** 
  53.      * 初始化 
  54.      *  
  55.      * @param context 
  56.      */  
  57.     public void init(Context context) {  
  58.         mContext = context;  
  59.         mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();// 獲取系統默認的UncaughtException處理器  
  60.         Thread.setDefaultUncaughtExceptionHandler(this);// 設置該CrashHandler爲程序的默認處理器  
  61.     }  
  62.   
  63.     /** 
  64.      * 當UncaughtException發生時會轉入該重寫的方法來處理 
  65.      */  
  66.     public void uncaughtException(Thread thread, Throwable ex) {  
  67.         if (!handleException(ex) && mDefaultHandler != null) {  
  68.             // 如果自定義的沒有處理則讓系統默認的異常處理器來處理  
  69.             mDefaultHandler.uncaughtException(thread, ex);  
  70.         } else {  
  71.             try {  
  72.                 Thread.sleep(3000);// 如果處理了,讓程序繼續運行3秒再退出,保證文件保存並上傳到服務器  
  73.             } catch (InterruptedException e) {  
  74.                 e.printStackTrace();  
  75.             }  
  76.             // 退出程序  
  77.             android.os.Process.killProcess(android.os.Process.myPid());  
  78.             System.exit(1);  
  79.         }  
  80.     }  
  81.   
  82.     /** 
  83.      * 自定義錯誤處理,收集錯誤信息 發送錯誤報告等操作均在此完成. 
  84.      *  
  85.      * @param ex 
  86.      *            異常信息 
  87.      * @return true 如果處理了該異常信息;否則返回false. 
  88.      */  
  89.     public boolean handleException(Throwable ex) {  
  90.         if (ex == null)  
  91.             return false;  
  92.         new Thread() {  
  93.             public void run() {  
  94.                 Looper.prepare();  
  95.                 Toast.makeText(mContext, "很抱歉,程序出現異常,即將退出"0).show();  
  96.                 Looper.loop();  
  97.             }  
  98.         }.start();  
  99.         // 收集設備參數信息  
  100.         collectDeviceInfo(mContext);  
  101.         // 保存日誌文件  
  102.         saveCrashInfo2File(ex);  
  103.         return true;  
  104.     }  
  105.   
  106.     /** 
  107.      * 收集設備參數信息 
  108.      *  
  109.      * @param context 
  110.      */  
  111.     public void collectDeviceInfo(Context context) {  
  112.         try {  
  113.             PackageManager pm = context.getPackageManager();// 獲得包管理器  
  114.             PackageInfo pi = pm.getPackageInfo(context.getPackageName(),  
  115.                     PackageManager.GET_ACTIVITIES);// 得到該應用的信息,即主Activity  
  116.             if (pi != null) {  
  117.                 String versionName = pi.versionName == null ? "null"  
  118.                         : pi.versionName;  
  119.                 String versionCode = pi.versionCode + "";  
  120.                 info.put("versionName", versionName);  
  121.                 info.put("versionCode", versionCode);  
  122.             }  
  123.         } catch (NameNotFoundException e) {  
  124.             e.printStackTrace();  
  125.         }  
  126.   
  127.         Field[] fields = Build.class.getDeclaredFields();// 反射機制  
  128.         for (Field field : fields) {  
  129.             try {  
  130.                 field.setAccessible(true);  
  131.                 info.put(field.getName(), field.get("").toString());  
  132.                 Log.d(TAG, field.getName() + ":" + field.get(""));  
  133.             } catch (IllegalArgumentException e) {  
  134.                 e.printStackTrace();  
  135.             } catch (IllegalAccessException e) {  
  136.                 e.printStackTrace();  
  137.             }  
  138.         }  
  139.     }  
  140.   
  141.     private String saveCrashInfo2File(Throwable ex) {  
  142.         StringBuffer sb = new StringBuffer();  
  143.         for (Map.Entry<String, String> entry : info.entrySet()) {  
  144.             String key = entry.getKey();  
  145.             String value = entry.getValue();  
  146.             sb.append(key + "=" + value + "\r\n");  
  147.         }  
  148.         Writer writer = new StringWriter();  
  149.         PrintWriter pw = new PrintWriter(writer);  
  150.         ex.printStackTrace(pw);  
  151.         Throwable cause = ex.getCause();  
  152.         // 循環着把所有的異常信息寫入writer中  
  153.         while (cause != null) {  
  154.             cause.printStackTrace(pw);  
  155.             cause = cause.getCause();  
  156.         }  
  157.         pw.close();// 記得關閉  
  158.         String result = writer.toString();  
  159.         sb.append(result);  
  160.         // 保存文件  
  161.         long timetamp = System.currentTimeMillis();  
  162.         String time = format.format(new Date());  
  163.         String fileName = "crash-" + time + "-" + timetamp + ".log";  
  164.         if (Environment.getExternalStorageState().equals(  
  165.                 Environment.MEDIA_MOUNTED)) {  
  166.             try {  
  167.                 File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +                           File.separator + "crash");  
  168.                 Log.i("CrashHandler", dir.toString());  
  169.                 if (!dir.exists())  
  170.                     dir.mkdir();  
  171.                 FileOutputStream fos = new FileOutputStream(new File(dir,  
  172.                          fileName));  
  173.                 fos.write(sb.toString().getBytes());  
  174.                 fos.close();  
  175.                 return fileName;  
  176.             } catch (FileNotFoundException e) {  
  177.                 e.printStackTrace();  
  178.             } catch (IOException e) {  
  179.                 e.printStackTrace();  
  180.             }  
  181.         }  
  182.         return null;  
  183.     }  
  184. }  

 

 然後,我們需要在應用啓動的時候在Application中註冊一下:

[java] view plaincopy
  1. package com.way.crash;  
  2.   
  3. import android.app.Application;  
  4.   
  5. public class CrashApplication extends Application {  
  6.     @Override  
  7.     public void onCreate() {  
  8.         super.onCreate();  
  9.         CrashHandler crashHandler = CrashHandler.getInstance();  
  10.         crashHandler.init(this);  
  11.     }  
  12. }  


最後,爲了讓我們的CrashApplication取代android.app.Application的地位,在我們的代碼中生效,我們需要修改AndroidManifest.xml:

[html] view plaincopy
  1. <application android:name=".CrashApplication"  
  2.        android:icon="@drawable/ic_launcher"  
  3.        android:label="@string/app_name"  
  4.        android:theme="@style/AppTheme" >  
  5.   ...  
  6. </application>  


因爲我們上面的CrashHandler中,遇到異常後要保存設備參數和具體異常信息到SDCARD,所以我們需要在AndroidManifest.xml中加入讀寫SDCARD權限:

[html] view plaincopy
  1. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  

搞定了上邊的步驟之後,我們來運行一下這個項目:

可以看到,並不會有強制關閉的對話框出現了,取而代之的是我們比較有好的提示信息。

然後看一下SDCARD生成的文件:

用文本編輯器打開日誌文件,看一段日誌信息:

[plain] view plaincopy
  1. CPU_ABI=armeabi  
  2. CPU_ABI2=unknown  
  3. ID=FRF91  
  4. MANUFACTURER=unknown  
  5. BRAND=generic  
  6. TYPE=eng  
  7. ......  
  8. Caused by: java.lang.NullPointerException  
  9.     at com.scott.crash.MainActivity.onCreate(MainActivity.java:13)  
  10.     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)  
  11.     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)  
  12.     ... 11 more  

這些信息對於開發者來說幫助極大,所以我們需要將此日誌文件上傳到服務器。


下面是一個以郵件形式提交錯誤報告的方法(2013年06月06日新增):

由於context爲非Activity的context,所以,我把彈出的對話框用了系統windows屬性,記得加上以下權限:

[html] view plaincopy
  1. <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>   

[java] view plaincopy
  1. /** 
  2.  * UncaughtException處理類,當程序發生Uncaught異常的時候,由該類來接管程序,並記錄發送錯誤報告. 
  3.  *  
  4.  * @author way 
  5.  *  
  6.  */  
  7. public class CrashHandler implements UncaughtExceptionHandler {  
  8.     private Thread.UncaughtExceptionHandler mDefaultHandler;// 系統默認的UncaughtException處理類  
  9.     private static CrashHandler INSTANCE;// CrashHandler實例  
  10.     private Context mContext;// 程序的Context對象  
  11.   
  12.     /** 保證只有一個CrashHandler實例 */  
  13.     private CrashHandler() {  
  14.   
  15.     }  
  16.   
  17.     /** 獲取CrashHandler實例 ,單例模式 */  
  18.     public static CrashHandler getInstance() {  
  19.         if (INSTANCE == null)  
  20.             INSTANCE = new CrashHandler();  
  21.         return INSTANCE;  
  22.     }  
  23.   
  24.     /** 
  25.      * 初始化 
  26.      *  
  27.      * @param context 
  28.      */  
  29.     public void init(Context context) {  
  30.         mContext = context;  
  31.   
  32.         mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();// 獲取系統默認的UncaughtException處理器  
  33.         Thread.setDefaultUncaughtExceptionHandler(this);// 設置該CrashHandler爲程序的默認處理器  
  34.     }  
  35.   
  36.     /** 
  37.      * 當UncaughtException發生時會轉入該重寫的方法來處理 
  38.      */  
  39.     public void uncaughtException(Thread thread, Throwable ex) {  
  40.         if (!handleException(ex) && mDefaultHandler != null) {  
  41.             // 如果自定義的沒有處理則讓系統默認的異常處理器來處理  
  42.             mDefaultHandler.uncaughtException(thread, ex);  
  43.         }  
  44.     }  
  45.   
  46.     /** 
  47.      * 自定義錯誤處理,收集錯誤信息 發送錯誤報告等操作均在此完成. 
  48.      *  
  49.      * @param ex 
  50.      *            異常信息 
  51.      * @return true 如果處理了該異常信息;否則返回false. 
  52.      */  
  53.     public boolean handleException(Throwable ex) {  
  54.         if (ex == null || mContext == null)  
  55.             return false;  
  56.         final String crashReport = getCrashReport(mContext, ex);  
  57.         Log.i("error", crashReport);  
  58.         new Thread() {  
  59.             public void run() {  
  60.                 Looper.prepare();  
  61.                 File file = save2File(crashReport);  
  62.                 sendAppCrashReport(mContext, crashReport, file);  
  63.                 Looper.loop();  
  64.             }  
  65.   
  66.         }.start();  
  67.         return true;  
  68.     }  
  69.   
  70.     private File save2File(String crashReport) {  
  71.         // TODO Auto-generated method stub  
  72.         String fileName = "crash-" + System.currentTimeMillis() + ".txt";  
  73.         if (Environment.getExternalStorageState().equals(  
  74.                 Environment.MEDIA_MOUNTED)) {  
  75.             try {  
  76.                 File dir = new File(Environment.getExternalStorageDirectory()  
  77.                         .getAbsolutePath() + File.separator + "crash");  
  78.                 if (!dir.exists())  
  79.                     dir.mkdir();  
  80.                 File file = new File(dir, fileName);  
  81.                 FileOutputStream fos = new FileOutputStream(file);  
  82.                 fos.write(crashReport.toString().getBytes());  
  83.                 fos.close();  
  84.                 return file;  
  85.             } catch (FileNotFoundException e) {  
  86.                 e.printStackTrace();  
  87.             } catch (IOException e) {  
  88.                 e.printStackTrace();  
  89.             }  
  90.         }  
  91.         return null;  
  92.     }  
  93.   
  94.     private void sendAppCrashReport(final Context context,  
  95.             final String crashReport, final File file) {  
  96.         // TODO Auto-generated method stub  
  97.         AlertDialog mDialog = null;  
  98.         AlertDialog.Builder builder = new AlertDialog.Builder(context);  
  99.         builder.setIcon(android.R.drawable.ic_dialog_info);  
  100.         builder.setTitle("程序出錯啦");  
  101.         builder.setMessage("請把錯誤報告以郵件的形式提交給我們,謝謝!");  
  102.         builder.setPositiveButton(android.R.string.ok,  
  103.                 new DialogInterface.OnClickListener() {  
  104.                     public void onClick(DialogInterface dialog, int which) {  
  105.   
  106.                         // 發送異常報告  
  107.                         try {  
  108.                             //註釋部分是已文字內容形式發送錯誤信息  
  109.                             // Intent intent = new Intent(Intent.ACTION_SENDTO);  
  110.                             // intent.setType("text/plain");  
  111.                             // intent.putExtra(Intent.EXTRA_SUBJECT,  
  112.                             // "推聊Android客戶端 - 錯誤報告");  
  113.                             // intent.putExtra(Intent.EXTRA_TEXT, crashReport);  
  114.                             // intent.setData(Uri  
  115.                             // .parse("mailto:[email protected]"));  
  116.                             // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  117.                             // context.startActivity(intent);  
  118.                               
  119.                             //下面是以附件形式發送郵件  
  120.                             Intent intent = new Intent(Intent.ACTION_SEND);  
  121.                             intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  122.                             String[] tos = { "[email protected]" };  
  123.                             intent.putExtra(Intent.EXTRA_EMAIL, tos);  
  124.   
  125.                             intent.putExtra(Intent.EXTRA_SUBJECT,  
  126.                                     "推聊Android客戶端 - 錯誤報告");  
  127.                             if (file != null) {  
  128.                                 intent.putExtra(Intent.EXTRA_STREAM,  
  129.                                         Uri.fromFile(file));  
  130.                                 intent.putExtra(Intent.EXTRA_TEXT,  
  131.                                         "請將此錯誤報告發送給我,以便我儘快修復此問題,謝謝合作!\n");  
  132.                             } else {  
  133.                                 intent.putExtra(Intent.EXTRA_TEXT,  
  134.                                         "請將此錯誤報告發送給我,以便我儘快修復此問題,謝謝合作!\n"  
  135.                                                 + crashReport);  
  136.                             }  
  137.                             intent.setType("text/plain");  
  138.                             intent.setType("message/rfc882");  
  139.                             Intent.createChooser(intent, "Choose Email Client");  
  140.                             context.startActivity(intent);  
  141.                         } catch (Exception e) {  
  142.                             Toast.makeText(context,  
  143.                                     "There are no email clients installed.",  
  144.                                     Toast.LENGTH_SHORT).show();  
  145.                         } finally {  
  146.                             dialog.dismiss();  
  147.                             // 退出  
  148.                             android.os.Process.killProcess(android.os.Process  
  149.                                     .myPid());  
  150.                             System.exit(1);  
  151.                         }  
  152.                     }  
  153.                 });  
  154.         builder.setNegativeButton(android.R.string.cancel,  
  155.                 new DialogInterface.OnClickListener() {  
  156.                     public void onClick(DialogInterface dialog, int which) {  
  157.                         dialog.dismiss();  
  158.                         // 退出  
  159.                         android.os.Process.killProcess(android.os.Process  
  160.                                 .myPid());  
  161.                         System.exit(1);  
  162.                     }  
  163.                 });  
  164.         mDialog = builder.create();  
  165.         mDialog.getWindow().setType(  
  166.                 WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);  
  167.         mDialog.show();  
  168.     }  
  169.   
  170.     /** 
  171.      * 獲取APP崩潰異常報告 
  172.      *  
  173.      * @param ex 
  174.      * @return 
  175.      */  
  176.     private String getCrashReport(Context context, Throwable ex) {  
  177.         PackageInfo pinfo = getPackageInfo(context);  
  178.         StringBuffer exceptionStr = new StringBuffer();  
  179.         exceptionStr.append("Version: " + pinfo.versionName + "("  
  180.                 + pinfo.versionCode + ")\n");  
  181.         exceptionStr.append("Android: " + android.os.Build.VERSION.RELEASE  
  182.                 + "(" + android.os.Build.MODEL + ")\n");  
  183.         exceptionStr.append("Exception: " + ex.getMessage() + "\n");  
  184.         StackTraceElement[] elements = ex.getStackTrace();  
  185.         for (int i = 0; i < elements.length; i++) {  
  186.             exceptionStr.append(elements[i].toString() + "\n");  
  187.         }  
  188.         return exceptionStr.toString();  
  189.     }  
  190.   
  191.     /** 
  192.      * 獲取App安裝包信息 
  193.      *  
  194.      * @return 
  195.      */  
  196.     private PackageInfo getPackageInfo(Context context) {  
  197.         PackageInfo info = null;  
  198.         try {  
  199.             info = context.getPackageManager().getPackageInfo(  
  200.                     context.getPackageName(), 0);  
  201.         } catch (NameNotFoundException e) {  
  202.             // e.printStackTrace(System.err);  
  203.             // L.i("getPackageInfo err = " + e.getMessage());  
  204.         }  
  205.         if (info == null)  
  206.             info = new PackageInfo();  
  207.         return info;  
  208.     }  
  209.   
  210. }  
發佈了26 篇原創文章 · 獲贊 8 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章