zoukankan      html  css  js  c++  java
  • Android中处理崩溃异常和记录日志(转)

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

        首先看一下效果图:

        

    一。在MainActivity.java代码中

    代码是这样写的:

    [java] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. public class MainActivity extends Activity {  
    2.       
    3.     private TextView tv;  
    4.   
    5.     @Override  
    6.     protected void onCreate(Bundle savedInstanceState) {  
    7.         super.onCreate(savedInstanceState);  
    8.         setContentView(R.layout.activity_main);  
    9.         tv.setText("我没初始化");  
    10.     }  
    11.   
    12.     @Override  
    13.     public boolean onCreateOptionsMenu(Menu menu) {  
    14.         // Inflate the menu; this adds items to the action bar if it is present.  
    15.         getMenuInflater().inflate(R.menu.main, menu);  
    16.         return true;  
    17.     }  
    18.   
    19. }  

    遇到软件没有捕获的异常之后,系统会弹出这个默认的强制关闭对话框。

    我们当然不希望用户看到这种现象,简直是对用户心灵上的打击,而且对我们的bug的修复也是毫无帮助的。我们需要的是软件有一个全局的异常捕获器,当出现一个我们没有发现的异常时,捕获这个异常,并且将异常信息记录下来,上传到服务器公开发这分析出现异常的具体原因。

    接下来我们就来实现这一机制,不过首先我们还是来了解以下两个类:android.app.Application和Java.lang.Thread.UncaughtExceptionHandler。

    Application:用来管理应用程序的全局状态。在应用程序启动时Application会首先创建,然后才会根据情况(Intent)来启动相应的Activity和Service。本示例中将在自定义加强版的Application中注册未捕获异常处理器。

    Thread.UncaughtExceptionHandler:线程未捕获异常处理器,用来处理未捕获异常。如果程序出现了未捕获异常,默认会弹出系统中强制关闭对话框。我们需要实现此接口,并注册为程序中默认未捕获异常处理。这样当未捕获异常发生时,就可以做一些个性化的异常处理操作。

    大家刚才在项目的结构图中看到的CrashHandler.java实现了Thread.UncaughtExceptionHandler,使我们用来处理未捕获异常的主要成员,代码如下:


    二:CrashHandler.java

    [java] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. public class CrashHandler implements UncaughtExceptionHandler {  
    2.   
    3.     public static String TAG = "MyCrash";  
    4.     // 系统默认的UncaughtException处理类  
    5.     private Thread.UncaughtExceptionHandler mDefaultHandler;  
    6.   
    7.     private static CrashHandler instance = new CrashHandler();  
    8.     private Context mContext;  
    9.   
    10.     // 用来存储设备信息和异常信息  
    11.     private Map<String, String> infos = new HashMap<String, String>();  
    12.   
    13.     // 用于格式化日期,作为日志文件名的一部分  
    14.     private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");  
    15.   
    16.     /** 保证只有一个CrashHandler实例 */  
    17.     private CrashHandler() {  
    18.     }  
    19.   
    20.     /** 获取CrashHandler实例 ,单例模式 */  
    21.     public static CrashHandler getInstance() {  
    22.         return instance;  
    23.     }  
    24.   
    25.     /** 
    26.      * 初始化 
    27.      *  
    28.      * @param context 
    29.      */  
    30.     public void init(Context context) {  
    31.         mContext = context;  
    32.         // 获取系统默认的UncaughtException处理器  
    33.         mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();  
    34.         // 设置该CrashHandler为程序的默认处理器  
    35.         Thread.setDefaultUncaughtExceptionHandler(this);  
    36.         autoClear(5);  
    37.     }  
    38.   
    39.     /** 
    40.      * 当UncaughtException发生时会转入该函数来处理 
    41.      */  
    42.     @Override  
    43.     public void uncaughtException(Thread thread, Throwable ex) {  
    44.         if (!handleException(ex) && mDefaultHandler != null) {  
    45.             // 如果用户没有处理则让系统默认的异常处理器来处理  
    46.             mDefaultHandler.uncaughtException(thread, ex);  
    47.         } else {  
    48.             SystemClock.sleep(1000);  
    49.             // 退出程序  
    50.             android.os.Process.killProcess(android.os.Process.myPid());  
    51.             System.exit(1);  
    52.         }  
    53.     }  
    54.   
    55.     /** 
    56.      * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成. 
    57.      *  
    58.      * @param ex 
    59.      * @return true:如果处理了该异常信息; 否则返回false. 
    60.      */  
    61.     private boolean handleException(Throwable ex) {  
    62.         if (ex == null)  
    63.             return false;  
    64.   
    65.         try {  
    66.             // 使用Toast来显示异常信息  
    67.             new Thread() {  
    68.   
    69.                 @Override  
    70.                 public void run() {  
    71.                     Looper.prepare();  
    72.                     Toast.makeText(mContext, "很抱歉,程序出现异常,即将重启.",  
    73.                             Toast.LENGTH_LONG).show();  
    74.                     Looper.loop();  
    75.                 }  
    76.             }.start();  
    77.             // 收集设备参数信息  
    78.             collectDeviceInfo(mContext);  
    79.             // 保存日志文件  
    80.             saveCrashInfoFile(ex);  
    81.             // 重启应用(按需要添加是否重启应用)  
    82. //            Intent intent = mContext.getPackageManager().getLaunchIntentForPackage(mContext.getPackageName());    
    83. //            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);    
    84. //            mContext.startActivity(intent);  
    85. //            SystemClock.sleep(1000);  
    86.         } catch (Exception e) {  
    87.             e.printStackTrace();  
    88.         }  
    89.   
    90.         return true;  
    91.     }  
    92.   
    93.     /** 
    94.      * 收集设备参数信息 
    95.      *  
    96.      * @param ctx 
    97.      */  
    98.     public void collectDeviceInfo(Context ctx) {  
    99.         try {  
    100.             PackageManager pm = ctx.getPackageManager();  
    101.             PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(),  
    102.                     PackageManager.GET_ACTIVITIES);  
    103.             if (pi != null) {  
    104.                 String versionName = pi.versionName + "";  
    105.                 String versionCode = pi.versionCode + "";  
    106.                 infos.put("versionName", versionName);  
    107.                 infos.put("versionCode", versionCode);  
    108.             }  
    109.         } catch (NameNotFoundException e) {  
    110.             Log.e(TAG, "an error occured when collect package info", e);  
    111.         }  
    112.         Field[] fields = Build.class.getDeclaredFields();  
    113.         for (Field field : fields) {  
    114.             try {  
    115.                 field.setAccessible(true);  
    116.                 infos.put(field.getName(), field.get(null).toString());  
    117.             } catch (Exception e) {  
    118.                 Log.e(TAG, "an error occured when collect crash info", e);  
    119.             }  
    120.         }  
    121.     }  
    122.   
    123.     /** 
    124.      * 保存错误信息到文件中 
    125.      * @param ex 
    126.      * @return 返回文件名称,便于将文件传送到服务器 
    127.      * @throws Exception 
    128.      */  
    129.     private String saveCrashInfoFile(Throwable ex) throws Exception {  
    130.         StringBuffer sb = new StringBuffer();  
    131.         try {  
    132.             SimpleDateFormat sDateFormat = new SimpleDateFormat(  
    133.                     "yyyy-MM-dd HH:mm:ss");  
    134.             String date = sDateFormat.format(new java.util.Date());  
    135.             sb.append(" " + date + " ");  
    136.             for (Map.Entry<String, String> entry : infos.entrySet()) {  
    137.                 String key = entry.getKey();  
    138.                 String value = entry.getValue();  
    139.                 sb.append(key + "=" + value + " ");  
    140.             }  
    141.   
    142.             Writer writer = new StringWriter();  
    143.             PrintWriter printWriter = new PrintWriter(writer);  
    144.             ex.printStackTrace(printWriter);  
    145.             Throwable cause = ex.getCause();  
    146.             while (cause != null) {  
    147.                 cause.printStackTrace(printWriter);  
    148.                 cause = cause.getCause();  
    149.             }  
    150.             printWriter.flush();  
    151.             printWriter.close();  
    152.             String result = writer.toString();  
    153.             sb.append(result);  
    154.   
    155.             String fileName = writeFile(sb.toString());  
    156.             return fileName;  
    157.         } catch (Exception e) {  
    158.             Log.e(TAG, "an error occured while writing file...", e);  
    159.             sb.append("an error occured while writing file... ");  
    160.             writeFile(sb.toString());  
    161.         }  
    162.         return null;  
    163.     }  
    164.   
    165.     private String writeFile(String sb) throws Exception {  
    166.         String time = formatter.format(new Date());  
    167.         String fileName = "crash-" + time + ".log";  
    168.         if (FileUtil.hasSdcard()) {  
    169.             String path = getGlobalpath();  
    170.             File dir = new File(path);  
    171.             if (!dir.exists())  
    172.                 dir.mkdirs();  
    173.   
    174.             FileOutputStream fos = new FileOutputStream(path + fileName, true);  
    175.             fos.write(sb.getBytes());  
    176.             fos.flush();  
    177.             fos.close();  
    178.         }  
    179.         return fileName;  
    180.     }  
    181.   
    182.     public static String getGlobalpath() {  
    183.         return Environment.getExternalStorageDirectory().getAbsolutePath()  
    184.                 + File.separator + "crash" + File.separator;  
    185.     }  
    186.       
    187.     public static void setTag(String tag) {  
    188.         TAG = tag;  
    189.     }  
    190.       
    191.     /** 
    192.      * 文件删除 
    193.      * @param day 文件保存天数 
    194.      */  
    195.     public void autoClear(final int autoClearDay) {  
    196.         FileUtil.delete(getGlobalpath(), new FilenameFilter() {  
    197.   
    198.             @Override  
    199.             public boolean accept(File file, String filename) {  
    200.                 String s = FileUtil.getFileNameWithoutExtension(filename);  
    201.                 int day = autoClearDay < 0 ? autoClearDay : -1 * autoClearDay;  
    202.                 String date = "crash-" + DateUtil.getOtherDay(day);  
    203.                 return date.compareTo(s) >= 0;  
    204.             }  
    205.         });  
    206.           
    207.     }  
    208.   
    209. }  

    在收集异常信息时,朋友们也可以使用Properties,因为Properties有一个很便捷的方法properties.store(OutputStream out, String comments),用来将Properties实例中的键值对外输到输出流中,但是在使用的过程中发现生成的文件中异常信息打印在同一行,看起来极为费劲,所以换成Map来存放这些信息,然后生成文件时稍加了些操作。

    完成这个CrashHandler后,我们需要在一个Application环境中让其运行,为此,我们继承android.app.Application,添加自己的代码,CrashApplication.java代码如下:

             三.MyAppcation

             

    [java] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. public class MyAppcation extends Application{  
    2.       
    3.     @Override  
    4.     public void onCreate() {  
    5.         super.onCreate();  
    6.         CrashHandler.getInstance().init(this);  
    7.     }  
    8.   
    9. }  

    因为我们上面的CrashHandler中,遇到异常后要保存设备参数和具体异常信息到SDCARD,所以我们需要在AndroidManifest.xml中加入读写SDCARD权限:

    1. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  

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

    源码下载地址:http://download.csdn.net/detail/u014608640/9626028

    转自:  

    Android中处理崩溃异常和记录日志

  • 相关阅读:
    Java实现 LeetCode 27 移除元素
    Java实现 LeetCode 26 删除排序数组中的重复项
    Java实现 LeetCode 26 删除排序数组中的重复项
    Java实现 LeetCode 26 删除排序数组中的重复项
    Java实现 LeetCode 25 K个一组翻转链表
    Java实现 LeetCode 25 K个一组翻转链表
    Java实现 LeetCode 25 K个一组翻转链表
    Java实现 LeetCode 24 两两交换链表中的节点
    Java实现 LeetCode 24 两两交换链表中的节点
    Java实现 LeetCode 24 两两交换链表中的节点
  • 原文地址:https://www.cnblogs.com/woaixingxing/p/6547174.html
Copyright © 2011-2022 走看看