Android 全局崩溃日志(CrashHandle)记录

                                                                                                                       
                                           

一、全局日志的初始化

在自定义Application中添加此方法,并在自定义Application的onCreate中调用


   
   
  1. private void initCrashhandle() {
  2.         CrashHandle crashHandler = CrashHandle.getInstance();
  3.         // 注册crashHandler
  4.         crashHandler.init(getApplicationContext());
  5.     }

二、CrashHandle类


   
   
  1. import android.content.Context;
  2. import android.content.SharedPreferences;
  3. import android.content.pm.PackageInfo;
  4. import android.content.pm.PackageManager;
  5. import android.content.pm.PackageManager.NameNotFoundException;
  6. import android.os.Build;
  7. import android.os.Looper;
  8. import android.util.Log;
  9. import android.widget.Toast;
  10. import com.adas.responsibleinvestigationplatform.greendao.daoutils.JDLogManage;
  11. import java.io.File;
  12. import java.io.FilenameFilter;
  13. import java.io.PrintWriter;
  14. import java.io.StringWriter;
  15. import java.io.Writer;
  16. import java.lang.Thread.UncaughtExceptionHandler;
  17. import java.lang.reflect.Field;
  18. import java.util.Arrays;
  19. import java.util.Properties;
  20. import java.util.TreeSet;
  21. public class CrashHandle implements UncaughtExceptionHandler {
  22.   /** Debug Log Tag */
  23.   public static final String TAG = "CrashHandler";
  24.   /** 是否开启日志输出, 在Debug状态下开启, 在Release状态下关闭以提升程序性能 */
  25.   public static final boolean DEBUG = true;
  26.   /** CrashHandler实例 */
  27.   private static CrashHandle INSTANCE;
  28.   /** 程序的Context对象 */
  29.   private Context mContext;
  30.   /** 系统默认的UncaughtException处理类 */
  31.   private UncaughtExceptionHandler mDefaultHandler;
  32.   /** 使用Properties来保存设备的信息和错误堆栈信息 */
  33.   private Properties mDeviceCrashInfo = new Properties();
  34.   private static final String VERSION_NAME = "versionName";
  35.   private static final String VERSION_CODE = "versionCode";
  36.   private static final String STACK_TRACE = "STACK_TRACE";
  37.   /** 错误报告文件的扩展名 */
  38.   private static final String CRASH_REPORTER_EXTENSION = ".cr";
  39.   /** 保证只有一个CrashHandler实例 */
  40.   private CrashHandle() {
  41.  }
  42.   /** 获取CrashHandler实例 */
  43.   public static synchronized CrashHandle getInstance() {
  44.    if (INSTANCE == null) {
  45.    INSTANCE = new CrashHandle();
  46.   }
  47.    return INSTANCE;
  48.  }
  49.   /**
  50.   * 初始化,注册Context对象, 获取系统默认的UncaughtException处理器, 设置该CrashHandler为程序的默认处理器
  51.   *
  52.   * @param ctx
  53.   */
  54.   @SuppressWarnings( "static-access")
  55.   public void init(Context ctx) {
  56.   mContext = ctx;
  57.   sp = mContext.getSharedPreferences( "config", mContext.MODE_PRIVATE);
  58.   mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
  59.   Thread.setDefaultUncaughtExceptionHandler( this);
  60.  }
  61.   private SharedPreferences sp;
  62.   @Override
  63.   public void uncaughtException(Thread thread, Throwable ex) {
  64.    if (!handleException(ex) && mDefaultHandler != null) {
  65.     // 如果用户没有处理则让系统默认的异常处理器来处理
  66.    mDefaultHandler.uncaughtException(thread, ex);
  67.   } else {
  68.     // Sleep一会后结束程序
  69.     // 来让线程停止一会是为了显示Toast信息给用户,然后Kill程序
  70.     try {
  71.     Thread.sleep( 3000);
  72.    } catch (InterruptedException e) {
  73.     Log.e(TAG, "Error : ", e);
  74.    }
  75.   
  76.   }
  77.   android.os.Process.killProcess(android.os.Process.myPid());
  78.   System.exit( 0);
  79.  }
  80.   /**
  81.   * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成. 开发者可以根据自己的情况来自定义异常处理逻辑
  82.   *
  83.   * @param ex
  84.   * @return true:如果处理了该异常信息;否则返回false
  85.   */
  86.   private boolean handleException(Throwable ex) {
  87.    if (ex == null) {
  88.     return true;
  89.   }
  90.    final String msg = ex.getLocalizedMessage();
  91.    // 使用Toast来显示异常信息
  92.    new Thread() {
  93.     @Override
  94.     public void run() {
  95.      // Toast 显示需要出现在一个线程的消息队列中
  96.     Looper.prepare();
  97.     Toast.makeText(mContext, "程序出错啦:" + msg, Toast.LENGTH_LONG).show();
  98.     Looper.loop();
  99.    }
  100.   }.start();
  101.    // 收集设备信息
  102.   collectCrashDeviceInfo(mContext);
  103.    /**
  104.    * 保存错误报告文件
  105.    * 在系统崩溃的时候可能会直接弹出app,没法发出错误日志
  106.    * 我没在这里发生错误日志【在项目启动页开启service来发送错误日志】
  107.    */
  108.   saveCrashInfoToFile(ex);
  109.    return true;
  110.  }
  111.   /**
  112.   * 收集程序崩溃的设备信息
  113.   *
  114.   * @param ctx
  115.   */
  116.   public void collectCrashDeviceInfo(Context ctx) {
  117.    try {
  118.     // Class for retrieving various kinds of information related to the
  119.     // application packages that are currently installed on the device.
  120.     // You can find this class through getPackageManager().
  121.    PackageManager pm = ctx.getPackageManager();
  122.     // getPackageInfo(String packageName, int flags)
  123.     // Retrieve overall information about an application package that is
  124.     // installed on the system.
  125.     // public static final int GET_ACTIVITIES
  126.     // Since: API Level 1 PackageInfo flag: return information about
  127.     // activities in the package in activities.
  128.    PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(),
  129.      PackageManager.GET_ACTIVITIES);
  130.     if (pi != null) {
  131.      // public String versionName The version name of this package,
  132.      // as specified by the <manifest> tag's versionName attribute.
  133.     mDeviceCrashInfo.put(VERSION_NAME,
  134.       pi.versionName == null ? "not set" : pi.versionName);
  135.      // public int versionCode The version number of this package,
  136.      // as specified by the <manifest> tag's versionCode attribute.
  137.     mDeviceCrashInfo.put(VERSION_CODE, pi.versionCode);
  138.    }
  139.   } catch (NameNotFoundException e) {
  140.    Log.e(TAG, "Error while collect package info", e);
  141.   }
  142.    // 使用反射来收集设备信息.在Build类中包含各种设备信息,
  143.    // 例如: 系统版本号,设备生产商 等帮助调试程序的有用信息
  144.    // 返回 Field 对象的一个数组,这些对象反映此 Class 对象所表示的类或接口所声明的所有字段
  145.   Field[] fields = Build.class.getDeclaredFields();
  146.    for (Field field : fields) {
  147.     try {
  148.      // setAccessible(boolean flag)
  149.      // 将此对象的 accessible 标志设置为指示的布尔值。
  150.      // 通过设置Accessible属性为true,才能对私有变量进行访问,不然会得到一个IllegalAccessException的异常
  151.     field.setAccessible( true);
  152.     mDeviceCrashInfo.put(field.getName(), field.get( null));
  153.      if (DEBUG) {
  154.      Log.d(TAG, field.getName() + " : " + field.get( null));
  155.     }
  156.    } catch (Exception e) {
  157.     Log.e(TAG, "Error while collect crash info", e);
  158.    }
  159.   }
  160.  }
  161.   /**
  162.   * 保存错误信息到文件中
  163.   *
  164.   * @param ex
  165.   * @return
  166.   */
  167.   private String saveCrashInfoToFile(Throwable ex) {
  168.   Writer info = new StringWriter();
  169.   PrintWriter printWriter = new PrintWriter(info);
  170.    // printStackTrace(PrintWriter s)
  171.    // 将此 throwable 及其追踪输出到指定的 PrintWriter
  172.   ex.printStackTrace(printWriter);
  173.    // getCause() 返回此 throwable 的 cause;如果 cause 不存在或未知,则返回 null。
  174.   Throwable cause = ex.getCause();
  175.    while (cause != null) {
  176.    cause.printStackTrace(printWriter);
  177.    cause = cause.getCause();
  178.   }
  179.    // toString() 以字符串的形式返回该缓冲区的当前值。
  180.   String result = info.toString();
  181.   printWriter.close();
  182.   mDeviceCrashInfo.put(STACK_TRACE, result);
  183.   String msg = mDeviceCrashInfo.toString();
  184.    /**
  185.    * 以下几行代码是手机错误信息的代码
  186.    * 1.JLog是自定义Log类,在这里打印崩溃日志
  187.    * 2.JDLogManage是自定义【数据库操作管理类】——用于保存、取出和删除崩溃日志
  188.    */
  189.   JLog.d(msg);
  190.    //生成错误日志并保存
  191.   JDLogManage manage = new JDLogManage(mContext);
  192.   manage.insertLog(msg);
  193.    return msg;
  194.  }
  195.   /**
  196.   * 把错误报告发送给服务器,包含新产生的和以前没发送的.
  197.   * 发送后标记为已发送/或者删除日志
  198.   * @param ctx
  199.   */
  200.   private void sendCrashReportsToServer(Context ctx) {
  201.   String[] crFiles = getCrashReportFiles(ctx);
  202.    if (crFiles != null && crFiles.length > 0) {
  203.    TreeSet<String> sortedFiles = new TreeSet<String>();
  204.    sortedFiles.addAll(Arrays.asList(crFiles));
  205.     for (String fileName : sortedFiles) {
  206.      //可回传文件
  207.     File cr = new File(ctx.getFilesDir(), fileName);
  208.     cr.delete(); // 删除已发送的报告
  209.    }
  210.   }
  211.  }
  212.   /**
  213.   * 获取错误报告文件名
  214.   *
  215.   * @param ctx
  216.   * @return
  217.   */
  218.   private String[] getCrashReportFiles(Context ctx) {
  219.   File filesDir = ctx.getFilesDir();
  220.    // 实现FilenameFilter接口的类实例可用于过滤器文件名
  221.   FilenameFilter filter = new FilenameFilter() {
  222.     // accept(File dir, String name)
  223.     // 测试指定文件是否应该包含在某一文件列表中。
  224.     public boolean accept(File dir, String name) {
  225.      return name.endsWith(CRASH_REPORTER_EXTENSION);
  226.    }
  227.   };
  228.    // list(FilenameFilter filter)
  229.    // 返回一个字符串数组,这些字符串指定此抽象路径名表示的目录中满足指定过滤器的文件和目录
  230.    return filesDir.list(filter);
  231.  }
  232.   /**
  233.   * 在程序启动时候, 可以调用该函数来发送以前没有发送的报告
  234.   */
  235.   public void sendPreviousReportsToServer() {
  236.   sendCrashReportsToServer(mContext);
  237.  }
  238. }

三、错误日志回传IntentService


   
   
  1. public class UploadJDLogService extends IntentService {
  2.     private JDLogManage manage;
  3.     private List<JDLog> logs;
  4.     private Gson gson;
  5.     public UploadJDLogService() {
  6.         super( "UploadJDLogService");
  7.     }
  8.     @Override
  9.     public void onCreate() {
  10.         super.onCreate();
  11.         gson = JApplication.getGson();
  12.         manage = new JDLogManage( this);
  13.         String userGuid = SharedPreferencesUtil.getUserGuid( this);
  14.         if (userGuid == null || userGuid == "") {
  15.             return;
  16.         }
  17.         logs = manage.getUnUploadLog(userGuid);
  18.     }
  19.     @Override
  20.     protected void onHandleIntent(Intent intent) {
  21.         if (logs != null && logs.size() > 0) {
  22.             for ( int i = 0; i < logs.size(); i++) {
  23.                 postLogs(logs.get(i));
  24.             }
  25.         }
  26.         stopSelf();
  27.     }
  28.     //回传日志
  29.     private void postLogs(JDLog log) {
  30.         final String JSONString = gson.toJson(log);
  31.         byte jsonbyte[];
  32.         try {
  33.             jsonbyte = JSONString.getBytes( "UTF-8"); //json转byte
  34.         } catch (Exception e) {
  35.             e.printStackTrace();
  36.             return;
  37.         }
  38.         String url = CommConfig.PATH.SendErrorLog;
  39.         try {
  40.             Response response = OkHttpUtils.postByte()
  41.                     .url(url)
  42.                     .content(jsonbyte)
  43.                     .build()
  44.                     .connTimeOut(Constant.Sorket_TimeOut)
  45.                     .readTimeOut(Constant.Sorket_TimeOut)
  46.                     .writeTimeOut(Constant.Sorket_TimeOut)
  47.                     .execute();
  48.             if (response.isSuccessful()) {
  49.                 String responseString = response.body().string();
  50.                 String result = URLResultPraise.praiseUnCompress(responseString, UploadJDLogService. this);
  51.                 ResultEntity result1 = new ResultEntity(result, UploadJDLogService. this);
  52.                 if (result1.isOk()) {
  53.                     manage.setUploaded(log);
  54.                     JLog.d( "日志回传成功");
  55.                 } else {
  56.                 }
  57.             } else {
  58.             }
  59.         } catch (IOException e) {
  60.             e.printStackTrace();
  61.         }
  62.     }
  63. }

4、数据库管理类【JDLog的属性可以通过此类推敲出来,就不展示了】【这里用了数据库框架greendao】


   
   
  1. public class JDLogManage {
  2.     private JDLogDao dao;
  3.     private Context context;
  4.     private final int clientType = 3; //1后台网址,3安卓督导Android,4ios督导 5安卓访员 6苹果访员
  5.     public JDLogManage(Context context) {
  6.         this.context = context;
  7.         dao = GreenDaoManager.getInstance().getUpdateSession(context).getJDLogDao();
  8.     }
  9.     /**
  10.      * 插入一个数据,返回插入的主键
  11.      *
  12.      * @param msg
  13.      * @return
  14.      */
  15.     public Long insertLog(String msg) {
  16.         if (msg == null) return null;
  17.         JDLog infoLog = new JDLog();
  18.         infoLog.setUserName(SharedPreferencesUtil.getUserName(context));
  19.         infoLog.setUserTel(SharedPreferencesUtil.getUserTelephone(context));
  20.         infoLog.setUserGuid(SharedPreferencesUtil.getUserGuid(context));
  21.         infoLog.setClientTime(Utils.getCurrentTime());
  22.         infoLog.setMechinecode(Utils.getDeviceIMEI(context));
  23.         infoLog.setUploadStatus( 0);
  24.         infoLog.setLogMsg(msg);
  25.         infoLog.setBrand(Build.BRAND);
  26.         infoLog.setSystemVersion(Utils.getSystemVersion());
  27.         infoLog.setAppVersion(CommConfig.VERSION);
  28.         infoLog.setClientType(clientType);
  29.         infoLog.setLogType( 1); //常规崩溃日志
  30.         infoLog.setDevMode(android.os.Build.MODEL);
  31.         return dao.insert(infoLog);
  32.     }
  33.     //获取未上传数据
  34.     public List<JDLog> getUnUploadLog(String userGuid) {
  35.         return dao.queryBuilder().where(JDLogDao.Properties.UploadStatus.eq( 0)).list();
  36.     }
  37.     //设置为已上传
  38.     public void setUploaded(JDLog log) {
  39.         if (log == null || log.getId() == null) return;
  40.         log.setUploadStatus( 1);
  41.         dao.update(log);
  42.     }
  43.     //删除已上传数据【备份回传后删除】
  44.     public void deleteAll() {
  45.         dao.deleteAll();
  46.     }
  47. }


                                   
                   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值