当前位置: 移动技术网 > 移动技术>移动开发>Android > 基于Android 错误信息捕获发送至服务器的详解

基于Android 错误信息捕获发送至服务器的详解

2019年07月24日  | 移动技术网移动技术  | 我要评论
程序员最头疼的事情就是bug和debug。这次debug长达20天,搞的我心力交瘁。累,因为android兼容性,不同手机会有不同的bug出来,而且很难复现,所以就上网找了下类似保存错误log到文件再上传到服务器,现把源码也共享出来。上传至服务器的代码我没加。相信大家都有现成的代码了。

先讲下原理,跟javaee的自定义异常捕获一样,将错误一直向上抛,然后在最上层统一处理。这里就可以获得exception message,进行保存操作
异常捕获类如下:
复制代码 代码如下:

/**
 * @author stay
 *      在application中统一捕获异常,保存到文件中下次再打开时上传
 */
public class crashhandler implements uncaughtexceptionhandler {  
    /** 是否开启日志输出,在debug状态下开启, 
     * 在release状态下关闭以提示程序性能 
     * */ 
    public static final boolean debug = true;  
    /** 系统默认的uncaughtexception处理类 */ 
    private thread.uncaughtexceptionhandler mdefaulthandler;  
    /** crashhandler实例 */ 
    private static crashhandler instance;  
    /** 程序的context对象 */ 
//    private context mcontext;  
    /** 保证只有一个crashhandler实例 */ 
    private crashhandler() {}  
    /** 获取crashhandler实例 ,单例模式*/ 
    public static crashhandler getinstance() {  
        if (instance == null) {  
            instance = new crashhandler();  
        }  
        return instance;  
    }  

    /** 
     * 初始化,注册context对象, 
     * 获取系统默认的uncaughtexception处理器, 
     * 设置该crashhandler为程序的默认处理器 
     *  
     * @param ctx 
     */ 
    public void init(context ctx) {  
//        mcontext = ctx;  
        mdefaulthandler = thread.getdefaultuncaughtexceptionhandler();  
        thread.setdefaultuncaughtexceptionhandler(this);  
    }  

    /** 
     * 当uncaughtexception发生时会转入该函数来处理 
     */ 
    @override 
    public void uncaughtexception(thread thread, throwable ex) {  
        if (!handleexception(ex) && mdefaulthandler != null) {  
            //如果用户没有处理则让系统默认的异常处理器来处理  
            mdefaulthandler.uncaughtexception(thread, ex);  
        } else {  //如果自己处理了异常,则不会弹出错误对话框,则需要手动退出app
            try {  
                thread.sleep(3000);  
            } catch (interruptedexception e) {  
            }  
            android.os.process.killprocess(android.os.process.mypid());  
            system.exit(10);  
        }  
    }  

    /** 
     * 自定义错误处理,收集错误信息 
     * 发送错误报告等操作均在此完成. 
     * 开发者可以根据自己的情况来自定义异常处理逻辑 
     * @return 
     * true代表处理该异常,不再向上抛异常,
     * false代表不处理该异常(可以将该log信息存储起来)然后交给上层(这里就到了系统的异常处理)去处理,
     * 简单来说就是true不会弹出那个错误提示框,false就会弹出
     */ 
    private boolean handleexception(final throwable ex) {  
        if (ex == null) {  
            return false;  
        }  
//        final string msg = ex.getlocalizedmessage();  
        final stacktraceelement[] stack = ex.getstacktrace();
        final string message = ex.getmessage();
        //使用toast来显示异常信息  
        new thread() {  
            @override 
            public void run() {  
                looper.prepare();  
//                toast.maketext(mcontext, "程序出错啦:" + message, toast.length_long).show();  
//                可以只创建一个文件,以后全部往里面append然后发送,这样就会有重复的信息,个人不推荐
                string filename = "crash-" + system.currenttimemillis()  + ".log";  
                file file = new file(environment.getexternalstoragedirectory(), filename);
                try {
                    fileoutputstream fos = new fileoutputstream(file,true);
                    fos.write(message.getbytes());
                    for (int i = 0; i < stack.length; i++) {
                        fos.write(stack[i].tostring().getbytes());
                    }
                    fos.flush();
                    fos.close();
                } catch (exception e) {
                }
                looper.loop();  
            }  

        }.start();  
        return false;  
    }  

    // todo 使用http post 发送错误报告到服务器  这里不再赘述
//    private void postreport(file file) {  
//      在上传的时候还可以将该app的version,该手机的机型等信息一并发送的服务器,
//      android的兼容性众所周知,所以可能错误不是每个手机都会报错,还是有针对性的去debug比较好
//    }  
}

在application oncreate时就注册exceptionhandler,此后只要程序在抛异常后就能捕获到。
复制代码 代码如下:

public class app extends application{
        @override 
        public void oncreate() {  
            super.oncreate();  
            crashhandler crashhandler = crashhandler.getinstance();  
            //注册crashhandler  
            crashhandler.init(getapplicationcontext());  
        }  
}
?public class logactivity extends activity {
    @override
    public void oncreate(bundle savedinstancestate) {
        super.oncreate(savedinstancestate);
        setcontentview(r.layout.main);
        try {//制造bug
            file file = new file(environment.getexternalstoragestate() ,"crash.bin");
            fileinputstream fis = new fileinputstream(file);
            byte[] buffer = new byte[1024];
            fis.read(buffer);
        } catch (exception e) {
            //这里不能再向上抛异常,如果想要将log信息保存起来,则抛出runtime异常,
//          让自定义的handler来捕获,统一将文件保存起来上传
            throw new runtimeexception(e);
        }
    }
}

注意,如果catch后不throw就默认是自己处理了,exceptionhandler不会捕获异常了。
再分享一个log的封装类,只要在这里设置debug的值就能让控制台是否打印出log
复制代码 代码如下:

public class debugutil {
    public static final string tag = "icon";
    public static final boolean debug = true;

    public static void toast(context context,string content){
        toast.maketext(context, content, toast.length_short).show();
    }

    public static void debug(string tag,string msg){
        if (debug) {
            log.d(tag, msg);
        }
    }

    public static void debug(string msg){
        if (debug) {
            log.d(tag, msg);
        }
    }

    public static void error(string tag,string error){
        log.e(tag, error);
    }

    public static void error(string error){
        log.e(tag, error);
    }
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网