详解Android全局异常的捕获处理
程序员文章站
2024-02-21 13:57:28
在android开发中在所难免的会出现程序crash,俗称崩溃。用户的随意性访问出现测试时未知的bug导致我们的程序crash,此时我们是无法直接获取的错误log的,也就无...
在android开发中在所难免的会出现程序crash,俗称崩溃。用户的随意性访问出现测试时未知的bug导致我们的程序crash,此时我们是无法直接获取的错误log的,也就无法修复bug。这就会极大的影响用户体验,此时我们需要注册一个功能来捕获全局的异常信息,当程序出现crash信息,我们把错误log记录下来,上传到服务器,以便于我们能及时修复bug。实现这个功能我们需要依赖于uncaughtexceptionhandler这个类,uncaughtexceptionhandler是一个接口,在thread中。里面只有一个方法uncaughtexception。当我们注册一个uncaughtexceptionhandler之后,当我们的程序crash时就会回调uncaughtexception方法,而uncaughtexception方法带有两个参数,参数中就存放这crash信息。接下来只看写代码
package hi.xiaoyu.crashhandler; import java.io.file; import java.io.filewriter; import java.io.ioexception; import java.lang.thread.uncaughtexceptionhandler; import java.util.date; import android.content.context; import android.os.environment; import android.util.log; public class crashhandler implements uncaughtexceptionhandler { private static crashhandler instance; public static crashhandler getinstance() { if (instance == null) { instance = new crashhandler(); } return instance; } public void init(context ctx) { thread.setdefaultuncaughtexceptionhandler(this); } /** * 核心方法,当程序crash 会回调此方法, throwable中存放这错误日志 */ @override public void uncaughtexception(thread arg0, throwable arg1) { string logpath; if (environment.getexternalstoragestate().equals( environment.media_mounted)) { logpath = environment.getexternalstoragedirectory() .getabsolutepath() + file.separator + file.separator + "log"; file file = new file(logpath); if (!file.exists()) { file.mkdirs(); } try { filewriter fw = new filewriter(logpath + file.separator + "errorlog.log", true); fw.write(new date() + "\n"); // 错误信息 // 这里还可以加上当前的系统版本,机型型号 等等信息 stacktraceelement[] stacktrace = arg1.getstacktrace(); fw.write(arg1.getmessage() + "\n"); for (int i = 0; i < stacktrace.length; i++) { fw.write("file:" + stacktrace[i].getfilename() + " class:" + stacktrace[i].getclassname() + " method:" + stacktrace[i].getmethodname() + " line:" + stacktrace[i].getlinenumber() + "\n"); } fw.write("\n"); fw.close(); // 上传错误信息到服务器 // uploadtoserver(); } catch (ioexception e) { log.e("crash handler", "load file failed...", e.getcause()); } } arg1.printstacktrace(); android.os.process.killprocess(android.os.process.mypid()); } }
在activity或者application中注册一下即可
crashhandler crashhandler = crashhandler.getinstance(); crashhandler.init(getapplicationcontext());
这样就实现了android全局异常的捕获处理,实现过程也比较简单,希望对大家学习android软件编程有所帮助。
上一篇: Python时间获取及转换知识汇总