Android将程序崩溃信息保存到本地文件

大家都知道,现在安装Android系统的手机版本和设备千差万别,在模拟器上运行良好的程序安装到某款手机上说不定就出现崩溃的现象,开发者个人不可能购买所有设备逐个调试,所以在程序发布出去之后,如果出现了崩溃现象,开发者应该及时获取在该设备上导致崩溃的信息,这对于下一个版本的bug修复帮助极大,所以今天就来介绍一下如何在程序崩溃的情况下收集相关的设备参数信息和具体的异常信息,并发送这些信息到服务器供开发者分析和调试程序。

 

源码下载地址http://download.csdn.net/detail/weidi1989/4588310

 

我们先建立一个crash项目,项目结构如图:

 

在MainActivity.Java代码中,故意制作一个错误的例子,以便于我们实验:

[java]  view plain  copy
  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 plain  copy
  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 plain  copy
  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 plain  copy
  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 plain  copy
  1. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  

搞定了上边的步骤之后,我们来运行一下这个项目:

可以看到,并不会有强制关闭的对话框出现了,取而代之的是我们比较有好的提示信息。

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

用文本编辑器打开日志文件,看一段日志信息:

[plain]  view plain  copy
  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 plain  copy
  1. <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>   

[java]  view plain  copy
  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:way.ping.li@gmail.com"));  
  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 = { "way.ping.li@gmail.com" };  
  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. }  
  211. 良心的公众号,更多精品文章,不要忘记关注哈

    《Android和Java技术栈》


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值