android 捕捉异常并上传至服务器的简单实现
程序员文章站
2023-08-21 22:57:32
在项目中,我们的应用经常会遇到崩溃的情况,如果你的项目已经发送到了应用市场上,那么应用发生的崩溃开发人员是开不到的,所以我们要想办法将异常信息传到服务器上,便于开发人员查看...
在项目中,我们的应用经常会遇到崩溃的情况,如果你的项目已经发送到了应用市场上,那么应用发生的崩溃开发人员是开不到的,所以我们要想办法将异常信息传到服务器上,便于开发人员查看并作出修改。google考虑到这一点,也提供了thread.uncaughtexceptionhandler接口来实现这一问题。
创建crash异常捕获很简单,主要的步骤有:
1.创建baseapplication继承application并实现thread.uncaughtexceptionhandler
2.通过thread.setdefaultuncaughtexceptionhandler(this)设置默认的异常捕获
3.最后在manifests中注册创建的baseapplication
一、异常捕捉的简单实用
public class baseapplication extends application implements thread.uncaughtexceptionhandler { @override public void oncreate() { super.oncreate(); //设置异常捕获 crashhandler catchhandler = crashhandler.getinstance(); catchhandler.init(this); } }
二、crashhandler(主要是实现uncaughtexception方法)
public class crashhandler implements 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"); myactivitylifecyclecallbacks mmyactivitylifecyclecallbacks = new myactivitylifecyclecallbacks(); /** 保证只有一个crashhandler实例 */ private crashhandler() { } /** 获取crashhandler实例 ,单例模式 */ public static crashhandler getinstance() { if (instance == null) instance = new crashhandler(); return instance; } /** * 初始化 */ public void init(sspapplication context) { mcontext = context; context.registeractivitylifecyclecallbacks(mmyactivitylifecyclecallbacks); // 获取系统默认的uncaughtexception处理器 mdefaulthandler = thread.getdefaultuncaughtexceptionhandler(); // 设置该crashhandler为程序的默认处理器 thread.setdefaultuncaughtexceptionhandler(this); } /** * 当uncaughtexception发生时会转入该函数来处理 */ @override public 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); // } // 注意thread.sleep(3000)和 systemclock.sleep(3000)的区别 systemclock.sleep(3000); // 退出程序 log.i("=====killprocess======","=====killprocess======"); mmyactivitylifecyclecallbacks.removeallactivities(); android.os.process.killprocess(android.os.process.mypid()); system.exit(0); } } /** * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成. * * @param ex * @return true:如果处理了该异常信息;否则返回false. */ private boolean handleexception(throwable ex) { log.i("=====handleexception======","=====handleexception======"); if (ex == null) { return false; } // 收集设备参数信息 collectdeviceinfo(mcontext); // 使用toast来显示异常信息 new thread() { @override public void run() { looper.prepare(); toast.maketext(mcontext, "哎呀,出问题了,我要暂时离开了", toast.length_short).show(); 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 (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(); sb.append(result); try { long timestamp = system.currenttimemillis(); string time = formatter.format(new date()); sharedpreferences userinfo = mcontext.getsharedpreferences( constants.user_setting_infos, 0); string loginname = userinfo.getstring(constants.username, ""); string filename = "crash-" + time +"-"+loginname+ ".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(final string filename) { if (!new file(filename).exists()) { toast.maketext(mcontext, "日志文件不存在!", toast.length_short).show(); return; } else { new thread(new runnable() { @override public void run() { looper.prepare(); arraylist<string> piclist = new arraylist<string>(); piclist.add(filename); sendeventpic sfile = new sendeventpic(mcontext); uuidgenerator generator = new uuidgenerator(); string linkid = generator.generate().tostring(); sharedpreferences userinfo = mcontext.getsharedpreferences( constants.user_setting_infos, 0); string loginname = userinfo.getstring(constants.username, ""); string userid = userinfo.getstring(constants.user_userid_infos, ""); boolean isproblempic = sfile.issendsuccess(piclist, linkid, "crash_tng", "crash_tng", loginname, userid); looper.loop(); } }).start(); } 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("info", s.tostring()); } } catch (filenotfoundexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } finally { // 关闭流 try { reader.close(); fis.close(); } catch (ioexception e) { e.printstacktrace(); } } } }
三、开发过程中遇到的坑
如果在activity创建的时候崩溃的话,系统有时候(目前不确定什么情况下会重启)会重启当前的activity,造成第二次的崩溃,如此循环……
所以,在应用崩溃时要完全退出应用。
public class myactivitylifecyclecallbacks implements activitylifecyclecallbacks { private list<activity> activities = new linkedlist<>(); public static int sanimationid = 0; @override public void onactivitycreated(activity activity, bundle savedinstancestate) { addactivity(activity); } @override public void onactivitystarted(activity activity) { } @override public void onactivityresumed(activity activity) { } @override public void onactivitypaused(activity activity) { } @override public void onactivitystopped(activity activity) { } @override public void onactivitysaveinstancestate(activity activity, bundle outstate) { } @override public void onactivitydestroyed(activity activity) { removeactivity(activity); } /** * 添加activity */ public void addactivity(activity activity) { if (activities == null) { activities = new linkedlist<>(); } if (!activities.contains(activity)) { activities.add(activity);// 把当前activity添加到集合中 } } /** * 移除activity */ public void removeactivity(activity activity) { if (activities.contains(activity)) { activities.remove(activity); } if (activities.size() == 0) { activities = null; } } /** * 销毁所有activity */ public void removeallactivities() { for (activity activity : activities) { if (null != activity) { activity.finish(); activity.overridependingtransition(0, sanimationid); } } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。