前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >如何方便的收集app崩溃日志

如何方便的收集app崩溃日志

作者头像
PhoenixZheng
发布2018-08-07 16:13:27
6150
发布2018-08-07 16:13:27
举报

在Thread中有个方法

代码语言:javascript
复制
setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler var0)

`

很多人可能没了解过这个东西可以干嘛用, 其实它的作用是可以传入一个 Handler来捕获那些没有被捕获的异常, 比如 app 层面的 crash。 下面提供了一段源码,可以用来捕获并把异常写入到文件中, 当然如果要上报的话也只需要把对应的字符串上报到统计系统就行。

代码语言:javascript
复制
public class ExceptionHandler implements Thread.UncaughtExceptionHandler {
    private static final String TAG = "ExceptionHandler";

    private static ExceptionHandler mInstance;
    private Context mContext;
    private SimpleDateFormat mFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");

    private ExceptionHandler() {
    }

    public static ExceptionHandler getInstance() {
        if(mInstance == null) {
            mInstance = new ExceptionHandler();
        }
        return mInstance;
    }

    public void init(Context context) {
        mContext = context;
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        try {
            Log.d(TAG, "uncaughtException: " + e.getMessage());
            File cache = mContext.getExternalCacheDir();
            String time = mFormat.format(new Date(System.currentTimeMillis()));
            String crashName = "crash_" + time + ".log";
            File crash = new File(cache, crashName);
            StringWriter stringWriter = new StringWriter();
            PrintWriter writer = new PrintWriter(stringWriter);
            e.getCause().printStackTrace(writer);
            writer.close();
            FileOutputStream fos = new FileOutputStream(crash, true);
            fos.write(stringWriter.toString().getBytes());
            fos.flush();
            fos.close();
            System.exit(0);
            Process.killProcess(Process.myPid());
        } catch (Exception exp) {
            Log.e(TAG, "uncaughtException: " + exp.getMessage());
            System.exit(0);
            Process.killProcess(Process.myPid());
        }
    }
}

`

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-07-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Android每日一讲 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档