Android应用全局异常处理

来源:互联网 发布:url转码方法 java 编辑:程序博客网 时间:2024/04/27 22:01

当我们做android客户端产品的时候为了让用户有更好的体验,我们需要拦截系统的异常弹出事件,并且将这些异常以比较“优雅”的方式反馈给用户,当然我们还要把这些异常提交到服务器上以便于程序员分析产生这些异常的原因,更好的维护和晚上这个android客户端产品.

首先在我们的application的oncreat()方法加入以下代码:

[java] view plaincopyprint?
  1.  MobclickAgent.onError(context);  
  2. andler crashHandler = CrashHandler.getInstance();    
  3. // 注册crashHandler    
  4. crashHandler.init(getApplicationContext());    

接着我们看crashHandler类:需要注意的一点是这里采用了友盟的sdk来上传异常信息,至于友盟怎么用:http://www.umeng.com/

[java] view plaincopyprint?
  1. import java.io.File;    
  2. import java.io.FileInputStream;  
  3. import java.io.FileOutputStream;    
  4. import java.io.FilenameFilter;    
  5. import java.io.PrintWriter;    
  6. import java.io.StringWriter;    
  7. import java.io.Writer;    
  8. import java.lang.Thread.UncaughtExceptionHandler;    
  9. import java.lang.reflect.Field;    
  10. import java.util.Arrays;    
  11. import java.util.Properties;    
  12. import java.util.TreeSet;    
  13.   
  14. import org.apache.http.util.EncodingUtils;  
  15.   
  16. import com.kaixin001.model.Setting;  
  17. import com.kaixin001.util.KXLog;  
  18. import com.umeng.analytics.MobclickAgent;  
  19.     
  20. import android.content.Context;    
  21. import android.content.pm.PackageInfo;    
  22. import android.content.pm.PackageManager;    
  23. import android.content.pm.PackageManager.NameNotFoundException;    
  24. import android.os.Build;    
  25. import android.os.Looper;    
  26. import android.widget.Toast;    
  27.     
  28. /**  
  29.  *   
  30.  *   
  31.  * UncaughtExceptionHandler:线程未捕获异常控制器是用来处理未捕获异常的。   
  32.  *                           如果程序出现了未捕获异常默认情况下则会出现强行关闭对话框  
  33.  *                           实现该接口并注册为程序中的默认未捕获异常处理   
  34.  *                           这样当未捕获异常发生时,就可以做些异常处理操作  
  35.  *                           例如:收集异常信息,发送错误报告 等。  
  36.  *   
  37.  * UncaughtException处理类,当程序发生Uncaught异常的时候,由该类来接管程序,并记录发送错误报告.  
  38.  */    
  39. public class CrashHandler implements UncaughtExceptionHandler {    
  40.     /** Debug Log Tag */    
  41.     public static final String TAG = "CrashHandler";    
  42.     /** CrashHandler实例 */    
  43.     private static CrashHandler INSTANCE;    
  44.     /** 程序的Context对象 */    
  45.     private Context mContext;    
  46.     /** 系统默认的UncaughtException处理类 */    
  47.     private Thread.UncaughtExceptionHandler mDefaultHandler;    
  48.       
  49.     private SendReports sendReports=null;  
  50.         
  51.     /** 使用Properties来保存设备的信息和错误堆栈信息 */    
  52.     private Properties mDeviceCrashInfo = new Properties();    
  53.     private static final String VERSION_NAME = "versionName";    
  54.     private static final String VERSION_CODE = "versionCode";    
  55.     private static final String STACK_TRACE = "STACK_TRACE";    
  56.     /** 错误报告文件的扩展名 */    
  57.     private static final String CRASH_REPORTER_EXTENSION = ".cr";    
  58.         
  59.     /** 保证只有一个CrashHandler实例 */    
  60.     private CrashHandler() {    
  61.     }    
  62.     
  63.     /** 获取CrashHandler实例 ,单例模式 */    
  64.     public static CrashHandler getInstance() {    
  65.         if (INSTANCE == null)    
  66.             INSTANCE = new CrashHandler();    
  67.         return INSTANCE;    
  68.     }    
  69.         
  70.     /**  
  71.      * 初始化,注册Context对象, 获取系统默认的UncaughtException处理器, 设置该CrashHandler为程序的默认处理器  
  72.      *   
  73.      * @param ctx  
  74.      */    
  75.     public void init(Context ctx) {    
  76.         mContext = ctx;    
  77.         mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();    
  78.         Thread.setDefaultUncaughtExceptionHandler(this);    
  79.     }    
  80.         
  81.     /**  
  82.      * 当UncaughtException发生时会转入该函数来处理  
  83.      */    
  84.     @Override    
  85.     public void uncaughtException(Thread thread, Throwable ex) {    
  86.         if (!handleException(ex) && mDefaultHandler != null) {    
  87.             // 如果用户没有处理则让系统默认的异常处理器来处理    
  88.             mDefaultHandler.uncaughtException(thread, ex);    
  89.         } else {    
  90.             // Sleep一会后结束程序    
  91.             // 来让线程停止一会是为了显示Toast信息给用户,然后Kill程序    
  92.             try {    
  93.                 Thread.sleep(4000);    
  94.             } catch (InterruptedException e) {    
  95.                 KXLog.e(TAG, "Error : ", e);    
  96.             }    
  97.             android.os.Process.killProcess(android.os.Process.myPid());    
  98.             System.exit(10);    
  99.         }    
  100.     }    
  101.     
  102.     /**  
  103.      * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成. 开发者可以根据自己的情况来自定义异常处理逻辑  
  104.      *   
  105.      * @param ex  
  106.      * @return true:如果处理了该异常信息;否则返回false  
  107.      */    
  108.     private boolean handleException(final Throwable ex) {    
  109.         if (ex == null) {    
  110.             return true;    
  111.         }    
  112.         final String msg = ex.getLocalizedMessage();    
  113.         // 使用Toast来显示异常信息    
  114.         new Thread() {    
  115.             @Override    
  116.             public void run() {    
  117.                 // Toast 显示需要出现在一个线程的消息队列中    
  118.                 Looper.prepare();    
  119.                 Toast.makeText(mContext, "程序出错啦,我们会尽快修改:" + msg, Toast.LENGTH_SHORT).show();    
  120.                 Looper.loop();    
  121.             }    
  122.         }.start();    
  123.           
  124.         // 收集设备信息    
  125.         collectCrashDeviceInfo(mContext);    
  126.         // 使用友盟SDK将错误报告保存到文件中,待下次应用程序重启时上传log  
  127.         String crashFileName = saveCrashInfoToFile(ex);    
  128.         // 发送错误报告到服务器  
  129.         //已经使用了友盟SDK上传,故此处注掉  
  130.         //sendCrashReportsToServer(mContext);    
  131.           
  132.         return true;    
  133.     }    
  134.     
  135.     /**  
  136.      * 收集程序崩溃的设备信息  
  137.      *   
  138.      * @param ctx  
  139.      */    
  140.     public void collectCrashDeviceInfo(Context ctx) {    
  141.         try {    
  142.             // Class for retrieving various kinds of information related to the    
  143.             // application packages that are currently installed on the device.    
  144.             // You can find this class through getPackageManager().    
  145.             PackageManager pm = ctx.getPackageManager();    
  146.             // getPackageInfo(String packageName, int flags)    
  147.             // Retrieve overall information about an application package that is installed on the system.    
  148.             // public static final int GET_ACTIVITIES    
  149.             // Since: API Level 1 PackageInfo flag: return information about activities in the package in activities.    
  150.             PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);    
  151.             if (pi != null) {    
  152.                 // public String versionName The version name of this package,    
  153.                 // as specified by the <manifest> tag's versionName attribute.    
  154.                 mDeviceCrashInfo.put(VERSION_NAME, pi.versionName == null ? "not set" : pi.versionName);    
  155.                 // public int versionCode The version number of this package,     
  156.                 // as specified by the <manifest> tag's versionCode attribute.    
  157.                 mDeviceCrashInfo.put(VERSION_CODE, String.valueOf(pi.versionCode));    
  158.             }   
  159.             //添加渠道号  
  160.             mDeviceCrashInfo.put("ctype", Setting.getInstance().getCType());  
  161.               
  162.         } catch (NameNotFoundException e) {    
  163.             KXLog.e(TAG, "Error while collect package info", e);    
  164.         }    
  165.         // 使用反射来收集设备信息.在Build类中包含各种设备信息,    
  166.         // 例如: 系统版本号,设备生产商 等帮助调试程序的有用信息    
  167.         // 返回 Field 对象的一个数组,这些对象反映此 Class 对象所表示的类或接口所声明的所有字段    
  168.         Field[] fields = Build.class.getDeclaredFields();    
  169.         for (Field field : fields) {    
  170.             try {    
  171.                 // setAccessible(boolean flag)    
  172.                 // 将此对象的 accessible 标志设置为指示的布尔值。    
  173.                 // 通过设置Accessible属性为true,才能对私有变量进行访问,不然会得到一个IllegalAccessException的异常    
  174.                 field.setAccessible(true);    
  175.                 mDeviceCrashInfo.put(field.getName(), String.valueOf(field.get(null)));    
  176.                 KXLog.d(TAG, field.getName() + " : " + field.get(null));    
  177.             } catch (Exception e) {    
  178.                 KXLog.e(TAG, "Error while collect crash info", e);    
  179.             }    
  180.         }    
  181.     }    
  182.         
  183.     /**  
  184.      * 保存错误信息到文件中  
  185.      *   
  186.      * @param ex  
  187.      * @return  
  188.      */    
  189.     private String saveCrashInfoToFile(Throwable ex) {    
  190.         Writer info = new StringWriter();    
  191.         PrintWriter printWriter = new PrintWriter(info);    
  192.         // printStackTrace(PrintWriter s)    
  193.         // 将此 throwable 及其追踪输出到指定的 PrintWriter    
  194.         ex.printStackTrace(printWriter);    
  195.     
  196.         // getCause() 返回此 throwable 的 cause;如果 cause 不存在或未知,则返回 null。    
  197.         Throwable cause = ex.getCause();    
  198.         while (cause != null) {    
  199.             cause.printStackTrace(printWriter);    
  200.             cause = cause.getCause();    
  201.         }    
  202.     
  203.         // toString() 以字符串的形式返回该缓冲区的当前值。    
  204.         String result = info.toString();    
  205.         printWriter.close();    
  206.         mDeviceCrashInfo.put(STACK_TRACE, result);    
  207.         KXLog.e(TAG, result);    
  208.         //友盟是现将错误信息保存在com_umeng__crash.cache文件中,然后在应用程序启动时调用MobclickAgent.onError(context);来启动一线程上传log  
  209.         String log=mDeviceCrashInfo.toString();  
  210.         MobclickAgent.reportError(mContext,log);  
  211.         return null;    
  212.     }    
  213.         
  214.     /**  
  215.      * 把错误报告发送给服务器,包含新产生的和以前没发送的.  
  216.      *   
  217.      * @param ctx  
  218.      */    
  219.     public void sendCrashReportsToServer(Context ctx) {    
  220.         String[] crFiles = getCrashReportFiles(ctx);    
  221.         if (crFiles != null && crFiles.length > 0) {    
  222.             TreeSet<String> sortedFiles = new TreeSet<String>();    
  223.             sortedFiles.addAll(Arrays.asList(crFiles));    
  224.     
  225.             for (String fileName : sortedFiles) {    
  226.                 File cr = new File(ctx.getFilesDir(), fileName);    
  227.                 postReport(ctx,cr);    
  228.                 cr.delete();// 删除已发送的报告    
  229.             }    
  230.         }    
  231.     }    
  232.     
  233.     /**  
  234.      * 获取错误报告文件名  
  235.      *   
  236.      * @param ctx  
  237.      * @return  
  238.      */    
  239.     private String[] getCrashReportFiles(Context ctx) {    
  240.         File filesDir = ctx.getFilesDir();    
  241.         // 实现FilenameFilter接口的类实例可用于过滤器文件名    
  242.         FilenameFilter filter = new FilenameFilter() {    
  243.             // accept(File dir, String name)    
  244.             // 测试指定文件是否应该包含在某一文件列表中。    
  245.             public boolean accept(File dir, String name) {    
  246.                 return name.endsWith(CRASH_REPORTER_EXTENSION);    
  247.             }    
  248.         };    
  249.         // list(FilenameFilter filter)    
  250.         // 返回一个字符串数组,这些字符串指定此抽象路径名表示的目录中满足指定过滤器的文件和目录    
  251.         return filesDir.list(filter);    
  252.     }    
  253.     
  254.     private void postReport(Context ctx,File file) {    
  255.         try{  
  256.             FileInputStream fin = new FileInputStream(file);  
  257.             StringBuffer localStringBuffer = new StringBuffer();  
  258.             byte [] buffer = new byte[1024];  
  259.             int i = 0;  
  260.             while ((i = fin.read(buffer)) != -1){  
  261.                 localStringBuffer.append(new String(buffer, 0, i));  
  262.             }  
  263.             fin.close();  
  264.             MobclickAgent.reportError(ctx,localStringBuffer.toString());  
  265.         }catch(Exception e){   
  266.             e.printStackTrace();   
  267.         }  
  268.     }    
  269.     
  270.     /**  
  271.      * 在程序启动时候, 可以调用该函数来发送以前没有发送的报告  
  272.      */    
  273.     public void sendPreviousReportsToServer() {   
  274.         if(null!=sendReports&&!sendReports.isAlive()){  
  275.             sendReports.start();  
  276.         }  
  277.     }    
  278.       
  279.     private final class SendReports extends Thread{  
  280.   
  281.         private Context mContext;   
  282.         private final Object lock = new Object();  
  283.           
  284.         public SendReports(Context mContext) {  
  285.             this.mContext=mContext;  
  286.         }  
  287.         public void run(){  
  288.             try{  
  289.                 synchronized (this.lock){  
  290.                     sendCrashReportsToServer(mContext);  
  291.                 }  
  292.             }catch(Exception e){  
  293.                 KXLog.e(TAG, "SendReports error.",e);  
  294.             }  
  295.         }  
  296.           
  297.     }  
  298. }    
原创粉丝点击