android 程序崩溃日记捕捉

1、重新UncaughtExceptionHandler

public class CrashHandler implements Thread.UncaughtExceptionHandler {public static final String TAG = "CrashHandler";//系统默认的UncaughtException处理类private Thread.UncaughtExceptionHandler mDefaultHandler;//CrashHandler实例private static CrashHandler instance;//程序的Context对象private Context mContext;//用来存储设备信息和异常信息private Map<String, String> infos = new HashMap<String, String>();//用于格式化日期,作为日志文件名的一部分private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");/** 保证只有一个CrashHandler实例 */private CrashHandler() {}/** 获取CrashHandler实例 ,单例模式 */public static CrashHandler getInstance() {if(instance == null)instance = new CrashHandler();return instance;}/*** 初始化*/public void init(Context context) {mContext = context;//获取系统默认的UncaughtException处理器mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();//设置该CrashHandler为程序的默认处理器Thread.setDefaultUncaughtExceptionHandler(this);}/*** 当UncaughtException发生时会转入该函数来处理*/@Overridepublic void uncaughtException(Thread thread, Throwable ex) {if (!handleException(ex) && mDefaultHandler != null) {//如果用户没有处理则让系统默认的异常处理器来处理mDefaultHandler.uncaughtException(thread, ex);} else {
//            try {
//                Thread.sleep(3000);
//            } catch (InterruptedException e) {
//                Log.e(TAG, "error : ", e);
//            }//退出程序android.os.Process.killProcess(android.os.Process.myPid());System.exit(1);}}/*** 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.** @param ex* @return true:如果处理了该异常信息;否则返回false.*/private boolean handleException(Throwable ex) {if (ex == null) {return false;}//收集设备参数信息collectDeviceInfo(mContext);
//        MyShareUtil.sharedPstring("updata","2");
//        Intent intent = new Intent(mContext, MainActivity.class);
//        mContext.startActivity(intent);//使用Toast来显示异常信息new Thread() {@Overridepublic void run() {Looper.prepare();Toast.makeText(mContext, "很抱歉,程序出现异常,即将退出", Toast.LENGTH_SHORT).show();
//                ToastUtil.showError(mContext, "很抱歉,程序出现异常,即将退出.", Toast.LENGTH_SHORT);Looper.loop();}}.start();//保存日志文件saveCatchInfo2File(ex);return true;}/*** 收集设备参数信息* @param ctx*/public void collectDeviceInfo(Context ctx) {try {PackageManager pm = ctx.getPackageManager();PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);if (pi != null) {String versionName = pi.versionName == null ? "null" : pi.versionName;String versionCode = pi.versionCode + "";infos.put("versionName", versionName);infos.put("versionCode", versionCode);}} catch (PackageManager.NameNotFoundException e) {Log.e(TAG, "an error occured when collect package info", e);}Field[] fields = Build.class.getDeclaredFields();for (Field field : fields) {try {field.setAccessible(true);infos.put(field.getName(), field.get(null).toString());Log.d(TAG, field.getName() + " : " + field.get(null));} catch (Exception e) {Log.e(TAG, "an error occured when collect crash info", e);}}}/*** 保存错误信息到文件中** @param ex* @return  返回文件名称,便于将文件传送到服务器*/private String saveCatchInfo2File(Throwable ex) {StringBuffer sb = new StringBuffer();for (Map.Entry<String, String> entry : infos.entrySet()) {String key = entry.getKey();String value = entry.getValue();sb.append(key + "=" + value + "\n");}Writer writer = new StringWriter();PrintWriter printWriter = new PrintWriter(writer);ex.printStackTrace(printWriter);Throwable cause = ex.getCause();while (cause != null) {cause.printStackTrace(printWriter);cause = cause.getCause();}printWriter.close();String result = writer.toString();Log.i("lgqqqqq======  ", result);sb.append(result);try {long timestamp = System.currentTimeMillis();String time = formatter.format(new Date());String fileName = "crash-" + time + "-" + timestamp + ".log";if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {String path = "/mnt/sdcard/crash/";File dir = new File(path);if (!dir.exists()) {dir.mkdirs();}FileOutputStream fos = new FileOutputStream(path + fileName);fos.write(sb.toString().getBytes());//发送给开发人员sendCrashLog2PM(path+fileName);fos.close();}return fileName;} catch (Exception e) {Log.e(TAG, "an error occured while writing file...", e);}return null;}/*** 将捕获的导致崩溃的错误信息发送给开发人员** 目前只将log日志保存在sdcard 和输出到LogCat中,并未发送给后台。*/private void sendCrashLog2PM(String fileName){if(!new File(fileName).exists()){
//            ToastUtil.showWarning(mContext, "日志文件不存在!", Toast.LENGTH_SHORT);Toast.makeText(mContext, "日志文件不存在", Toast.LENGTH_SHORT).show();return;}FileInputStream fis = null;BufferedReader reader = null;String s = null;try {fis = new FileInputStream(fileName);reader = new BufferedReader(new InputStreamReader(fis, "GBK"));while(true){s = reader.readLine();if(s == null) break;//由于目前尚未确定以何种方式发送,所以先打出log日志。Log.i("lgqqqq", s.toString());//                Intent data=new Intent(Intent.ACTION_SENDTO);
//                data.setData(Uri.parse("mailto:1085220040@qq.com"));
//                data.putExtra(Intent.EXTRA_SUBJECT, "这是标题");
//                data.putExtra(Intent.EXTRA_TEXT, "这是内容"+s.toString());
//                mContext.startActivity(data);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally{   // 关闭流try {reader.close();fis.close();} catch (IOException e) {e.printStackTrace();}}}
}

2、在Application类启动自定义类即可

CrashHandler catchHandler = CrashHandler.getInstance();
catchHandler.init(getApplicationContext());

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/415806.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

车型数据库设计 mongodb

直接上代码了 const mongoose require(mongoose); const Schema mongoose.Schema;// 汽车索引列表 const CarListSchema new mongoose.Schema({// 首字母 A、B、C...initial: String,// 汽车品牌分类category: [{// 首字母initial: String,// 拼音pinyin: Array,// 汽车大品…

洛谷 P3102 [USACO14FEB]秘密代码Secret Code

P3102 [USACO14FEB]秘密代码Secret Code 题目描述 Farmer John has secret message that he wants to hide from his cows; the message is a string of length at least 2 containing only the characters A..Z. To encrypt his message, FJ applies a sequence of "oper…

iview tag 标签点击事件

iview的tag组件有一个地方比较奇怪&#xff0c;就是默认只有on-close事件。 当我们想点击关闭和激活tag组件的时候&#xff0c;我们只能自己进行维护。 需要只用click.native进行控制 <Tag color"red" :checkable"true" :checked"false" clic…

android 获取url中的参数,验证邮箱格式,截取字符串中键值对的值,String的字节长度,去空格,替换字符

String ss"hello"; byte[] buffss.getBytes(); int fbuff.length; System.out.println(f); 字节长度。一个中文是3。其他是1 1、获取url中的参数 创建string String urls "http://www.yxtribe.com/yuanxinbuluo/weixin/getJsp?urlwechatweb/business-style-f…

oracle数据导入与导出

数据的导入导出 说明&#xff1a; 针对的对象&#xff1a; 数据的导入导出牵涉到的角色主要是工程实施人员。 需解决的问题&#xff1a;把所需要的数据从一个数据库中导入到另外一个数据库中。 1 工具方式 1.1 工具说明 1. 使用PLSQL Developer工具主要为了…

ubuntu中使用apt-get安装zbar

apt-get是linux中常用的shell命令&#xff0c;适用于deb包管理式的操作系统&#xff0c;主要用于自动从互联网的软件仓库中搜索、安装、升级、卸载软件或操作系统。apt-get命令一般需要root权限执行&#xff0c;所以前边一般跟着sudo命令。 Zbar是一个开源的二维码&#xff08;…

微信红包 开发前的准备

今天的开发目标是实现微信红包功能。先记录需要进行微信红包开发前的准备工作。 1、进行微信支付&#xff1a;需要注册认证的服务号或者认证的企业号 2、若要进行红包开发&#xff0c;前置准备条件 入住时间超过90天&#xff1b;连续交易正常交易时间30天&#xff1b; 3、微…

QC安装与运行中的问题汇集

服务器localhost127.0.0.1一、QC安装成功&#xff0c;但服务无法启动QC在安装过程中最容易出问题的就是SQL和jbossSQL ,JBOSS, QC三个启动都是独立的。托盘qc启动成功并不表示成功启动jboss,不加qcbin试试看&#xff0c;能确认jboss是否启动成功。如果JBOSS启动失败往往有以下几…

android 屏幕横竖屏切换时生命周期运行详解,创建横屏layout,has no declaration in the base

横屏代码 1、配置文件设置 android:screenOrientation"landscape" 2、java代码设置 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//hp 竖屏代码 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);//sp activit…

CodeForces 580A Kefa and First Steps

Time limit 2000 ms Memory limit 262144 kB Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes ai money. Kefa loves progress, thats why he wants to know the length of…

微信支付 商户Key 支付Key API密钥 的获取

读了微信支付的开发文档&#xff0c;感觉是不同阶段&#xff0c;不同的同学写的&#xff0c;有些专业名词比较混乱&#xff0c;甚至还会有错别字&#xff0c;以及接口更新了&#xff0c;而文档不更新的情况。 使用微信支付&#xff0c;必须要用到 api密钥进行签名 其中 &…

oracle 10g 报错:ORA-00257: archiver error. Connect internal only, until freed

今天在公司&#xff0c;突然同事告诉我数据库无法登录了&#xff0c;想想这段时间没有动过库&#xff0c;为什么无法登录呢&#xff1f;一边想是什么问题&#xff0c;一边连接测试登录。 首先报错&#xff1a;ORA-00257: archiver error. Connect internal only, until freed.…

android 获取键盘回车键事件,设置软键盘回车键显示内容,点击空白处隐藏软键盘

首先设置EditText的回车属性 drawable文件 drawable/editcolor <?xml version"1.0" encoding"utf-8"?> <shape xmlns:android"http://schemas.android.com/apk/res/android" android:shape"rectangle"><size andro…

微信支付 签名算法 sign node实现

开发微信支付过程中&#xff0c;第一道门槛就是微信支付接口签名&#xff0c;只要按照官方文档写&#xff0c;就不会有什么错。 1、官方签名文档地址 https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter4_3 2、我的实现 // 获取微信签名 getSign: (para…

触发器定义

create trigger atf on dbo.a after insertasbegin truncate table aend转载于:https://www.cnblogs.com/huanglong1987/p/7587570.html

android RecyclerView EditText 取消自动聚焦

在manifest中的activity中配置 android:windowSoftInputMode"adjustPan"