使用anrwatchdog抓取错误日志

本文介绍了如何通过ANR-WatchDog库来监控并捕获Android应用的错误日志。通过在build.gradle中引入该库,开发者可以更有效地调试和解决应用程序无响应(ANR)问题。

github网址:https://github.com/SalomonBrys/ANR-WatchDog
buld.gradle 中引入implementation 'com.github.anrwatchdog:anrwatchdog:1.4.0'


public class WatchDogUtils {

    public static final int WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 1001;
    private static final String ADR_DUMP_PATH = "anrHprof";
    private static File mExternalReportPath;
    private static ANRWatchDog anrWatchDog;

    public static void startAnrWatch(Context context) {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                    (Activity) context,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
        } else {
            initANRWatchDog(context);
        }
    }
    public static void closeANRWatchDog(Context context) {

    }
    public static void initANRWatchDog(Context context) {
        if (mExternalReportPath == null) {
            mExternalReportPath = new File(context.getFilesDir(), ADR_DUMP_PATH);
            if (!mExternalReportPath.exists()) {
                mExternalReportPath.mkdirs();
            }
        }
        if (anrWatchDog == null) {
            anrWatchDog = new ANRWatchDog();
        }
        anrWatchDog
                .setANRListener(new ANRWatchDog.ANRListener() {
                    @Override
                    public void onAppNotResponding(ANRError error) {
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
                        Date date = new Date(System.currentTimeMillis());
                        String name = "anr" + formatter.format(date);
                        File anr = new File(mExternalReportPath, name);
                        try {
                            Debug.dumpHprofData(anr.getAbsolutePath());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                })
                .start();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值